Skip to content

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

feat(mcp): package dependency summary in get_overview (#2749)

Raghav Chamadiyad4c611ad719f
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 0702fc5c5..e4085553a 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -295,7 +295,7 @@ The architecture map: summary, key modules, entry points, layers, code and git h
| `include` | list[string] | none | Any of `content` (full essay), `outline` (wiki page tree), `tour` (guided tour and reading order), `decisions`, `graph` (community clusters), `ownership` (top owners) |
| `repo` | string | default repo | Workspace repo alias, or `"all"` for the cross-repo topology |
-**Key return fields:** `title`, `content_md` (summary section by default), `key_modules`, `entry_points`, `architecture`, `code_health`, `git_health`, `next_actions`, `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.
+**Key return fields:** `title`, `content_md` (summary section by default), `key_modules`, `entry_points`, `architecture` (layers in stack order, plus `dependencies`: the ten heaviest package-to-package edges with `from`, `to`, `verb` and `weight`, and `edges_total` when more exist; absent in a single-package repo), `code_health`, `git_health`, `next_actions`, `more` (names the opt-in blocks), and a `workspace` footer in workspace mode.
```
get_overview()
diff --git a/packages/core/src/repowise/core/analysis/c4/relations.py b/packages/core/src/repowise/core/analysis/c4/relations.py
index 1d3f7d41e..e268cb52a 100644
--- a/packages/core/src/repowise/core/analysis/c4/relations.py
+++ b/packages/core/src/repowise/core/analysis/c4/relations.py
@@ -4,7 +4,9 @@ Each endpoint maps to its box (a container, a component, or an external
system), counts are summed per directed box pair with the edge types seen, and
self-loops are dropped. Co-change edges are history, not a dependency, so they
are left out unless a caller opts in. Edges touching a configuration file are
-dropped: reading config is not a dependency between boxes.
+dropped: reading config is not a dependency between boxes. Edges touching a
+test file are dropped too: a test importing a package is not a dependency of
+the box the test sits in.
"""
from __future__ import annotations
@@ -13,6 +15,7 @@ from collections import defaultdict
from collections.abc import Iterable, Mapping
from repowise.core.support_paths import is_config_path
+from repowise.core.test_paths import is_test_related_path
#: ``(source box, target box) -> (file-pair count, edge types)``.
BoxEdges = dict[tuple[str, str], tuple[int, frozenset[str]]]
@@ -45,6 +48,8 @@ def roll_up_edges(
continue
if is_config_path(src) or is_config_path(tgt):
continue
+ if is_test_related_path(src) or is_test_related_path(tgt):
+ continue
counts[(src_box, tgt_box)] += 1
types[(src_box, tgt_box)].add(etype)
return {key: (count, frozenset(types[key])) for key, count in counts.items()}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py b/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py
index ee1c5f91b..87b6e35b3 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py
@@ -1,7 +1,8 @@
-"""Graph-derived overview blocks: code communities and architecture layers."""
+"""Graph-derived overview blocks: code communities, layers and package dependencies."""
from __future__ import annotations
+import copy
import json
from collections import Counter, defaultdict
from typing import Any
@@ -17,6 +18,22 @@ from repowise.core.persistence.crud import (
)
from repowise.core.persistence.models import GraphNode
from repowise.server.mcp_server._helpers import filter_graph_nodes
+from repowise.server.mcp_server._index_state import index_state_key
+from repowise.server.services.c4_builder import container_dependencies
+
+#: Heaviest package edges the overview carries; the container view draws them all.
+_DEPENDENCY_EDGES = 10
+
+# The roll-up reads every graph edge, and it changes only with the index, so it
+# is cached per repo, index state and exclusion rules (the compiled rule set is
+# itself cached, so its identity is stable while the rules are).
+_DEPENDENCY_CACHE: dict[tuple[str, str, int], dict[str, Any]] = {}
+_DEPENDENCY_CACHE_LIMIT = 16
+
+
+def reset_cache() -> None:
+ """Drop every cached dependency block. For tests and an in-process re-index."""
+ _DEPENDENCY_CACHE.clear()
async def _load_community_nodes(
@@ -110,3 +127,45 @@ async def _build_architecture(session: Any, repository: Any) -> dict[str, Any]:
"tour_available": bool(kg_tour),
"tour_step_count": len(kg_tour),
}
+
+
+async def _build_package_dependencies(
+ session: Any, repository: Any, exclude_spec: Any = None
+) -> dict[str, Any]:
+ """Package-to-package edges, heaviest first; empty for a single-package repo.
+
+ The containers and roll-up are the container view's, so test files add no
+ weight in either. ``weight`` counts the file pairs behind an edge.
+ """
+ key = (repository.id, index_state_key(repository), id(exclude_spec))
+ cached = _DEPENDENCY_CACHE.get(key)
+ if cached is None:
+ cached = await _package_dependencies(session, repository.id, exclude_spec)
+ if len(_DEPENDENCY_CACHE) >= _DEPENDENCY_CACHE_LIMIT:
+ _DEPENDENCY_CACHE.clear()
+ _DEPENDENCY_CACHE[key] = cached
+ # A copy: the response is shaped after this returns.
+ return copy.deepcopy(cached)
+
+
+async def _package_dependencies(session: Any, repo_id: str, exclude_spec: Any) -> dict[str, Any]:
+ containers, relations = await container_dependencies(
+ session, repo_id, exclude_spec=exclude_spec
+ )
+ path_of = {c.id: c.path or "." for c in containers}
+ edges = [
+ {
+ "from": path_of[r.source_id],
+ "to": path_of[r.target_id],
+ "verb": r.label,
+ "weight": r.edge_count,
+ }
+ for r in relations[:_DEPENDENCY_EDGES]
+ if r.source_id in path_of and r.target_id in path_of
+ ]
+ if not edges:
+ return {}
+ block: dict[str, Any] = {"edges": edges}
+ if len(relations) > len(edges):
+ block["edges_total"] = len(relations)
+ return block
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
index 95e65e300..ff17d23ce 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
@@ -26,6 +26,7 @@ from repowise.server.mcp_server.tool_overview.decisions import _build_key_decisi
from repowise.server.mcp_server.tool_overview.graph import (
_build_architecture,
_build_community_summary,
+ _build_package_dependencies,
_load_community_nodes,
)
from repowise.server.mcp_server.tool_overview.health import _build_code_health
@@ -57,8 +58,8 @@ from repowise.server.mcp_server.tool_overview.workspace import (
async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:
"""Architecture map for an unfamiliar repo — first call when you don't know your way around.
- Returns the synthesised overview summary, key modules, entry points,
- architecture layers, code health, repo-wide git health, and
+ Returns the overview summary, key modules, entry points, architecture
+ layers and package dependencies, code health, repo-wide git health, and
``next_actions`` (top work for the week and quarter).
Skip this on subsequent calls — once you have the map, jump straight to
``get_context`` / ``get_answer``.
@@ -121,6 +122,9 @@ async def _repo_overview(
entry_point_ids = await _resolve_entry_point_ids(session, repository, exclude_spec)
all_git = await _load_git_rows(session, repository, exclude_spec)
architecture = await _build_architecture(session, repository)
+ dependencies = await _build_package_dependencies(session, repository, exclude_spec)
+ if dependencies:
+ architecture = {**architecture, "dependencies": dependencies}
code_health = await _build_code_health(session, repository)
next_actions, next_actions_reason = await _build_next_actions(session, repository)
requested = await _requested_blocks(session, repository, exclude_spec, all_git, want)
diff --git a/packages/server/src/repowise/server/services/c4_builder/__init__.py b/packages/server/src/repowise/server/services/c4_builder/__init__.py
index 1ce84453b..b0feae31f 100644
--- a/packages/server/src/repowise/server/services/c4_builder/__init__.py
+++ b/packages/server/src/repowise/server/services/c4_builder/__init__.py
@@ -20,11 +20,13 @@ import json
from collections import defaultdict
from dataclasses import replace
from pathlib import Path
+from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.c4.actors import derive_actors
+from repowise.core.exclusion import is_excluded
from repowise.core.ids import ExternalSystemId, SystemId, file_path_of, parse, render
from repowise.core.ingestion.workspace_members import root_description
from repowise.core.persistence import ExternalSystem, Repository
@@ -72,6 +74,7 @@ __all__ = [
"build_l2",
"build_l3",
"build_model",
+ "container_dependencies",
"container_id",
"load_repo",
]
@@ -241,6 +244,25 @@ async def build_l2(
return C4L2(containers=containers, external_systems=pruned_externals, relations=relations)
+async def container_dependencies(
+ session: AsyncSession, repo_id: str, *, exclude_spec: Any = None
+) -> tuple[list[Container], list[Relation]]:
+ """Containers and the relations between them: :func:`build_l2`'s boxes and
+ roll-up, without externals or box signals.
+
+ Files matching *exclude_spec* map to no box, so their edges never land.
+ """
+ repo = await load_repo(session, repo_id)
+ containers = await _detect_containers(session, repo_id, repo)
+ file_to_container = {
+ path: box
+ for path, box in (await _file_to_container_map(session, repo_id, containers)).items()
+ if not is_excluded(path, exclude_spec)
+ }
+ relations = await aggregate_relations(session, repo_id, file_to_box=file_to_container)
+ return containers, relations
+
+
async def build_l3(session: AsyncSession, repo_id: str, container_id_value: str) -> C4L3 | None:
"""Return L3 view for one container, or ``None`` if it doesn't exist."""
repo = await load_repo(session, repo_id)
diff --git a/tests/conftest.py b/tests/conftest.py
index be2409b61..f4da7dff1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -118,7 +118,7 @@ def _fresh_per_index_caches():
so every test's index looks the same to the cache key. Looked up in
``sys.modules`` so a test that never loads the server pays nothing.
"""
- for name in ("_basis", "_scope", "_graph_files"):
+ for name in ("_basis", "_scope", "_graph_files", "tool_overview.graph"):
module = sys.modules.get(f"repowise.server.mcp_server.{name}")
if module is not None:
module.reset_cache()
diff --git a/tests/unit/server/services/test_c4_builder.py b/tests/unit/server/services/test_c4_builder.py
index 9a71b9d7e..91c99a886 100644
--- a/tests/unit/server/services/test_c4_builder.py
+++ b/tests/unit/server/services/test_c4_builder.py
@@ -381,3 +381,114 @@ async def test_l2_skips_edges_to_config_files(async_session):
"pkg:packages/a",
1,
)
+
+
+async def _add_test_import(session, repo) -> None:
+ """A test in web importing core: not a dependency of web on core."""
+ await batch_upsert_graph_nodes(
+ session,
+ repo.id,
+ [{"node_id": "packages/web/tests/test_api.py", "node_type": "file", "language": "python", "symbol_count": 1}],
+ )
+ await batch_upsert_graph_edges(
+ session,
+ repo.id,
+ [{"source_node_id": "packages/web/tests/test_api.py", "target_node_id": "packages/core/ingestion/graph.py", "edge_type": "imports"}],
+ )
+ await session.commit()
+
+
+def test_roll_up_drops_edges_touching_a_test_file():
+ from repowise.core.analysis.c4.relations import roll_up_edges
+
+ boxes = {"a/src/x.py": "a", "a/tests/test_x.py": "a", "b/src/y.py": "b"}
+ rolled = roll_up_edges(
+ [
+ ("a/src/x.py", "b/src/y.py", "imports"),
+ ("a/tests/test_x.py", "b/src/y.py", "imports"),
+ ],
+ boxes,
+ )
+ assert rolled == {("a", "b"): (1, frozenset({"imports"}))}
+
+
+async def test_container_view_and_dependencies_agree_without_tests(async_session):
+ repo = await _seed_monorepo(async_session)
+ await _add_test_import(async_session, repo)
+
+ containers, relations = await c4_builder.container_dependencies(async_session, repo.id)
+ view = await c4_builder.build_l2(async_session, repo.id)
+
+ assert {c.path for c in containers} == {"packages/core", "packages/web"}
+ internal = [(r.source_id, r.target_id, r.edge_count) for r in relations]
+ assert internal == [("pkg:packages/web", "pkg:packages/core", 1)]
+ in_view = [
+ (r.source_id, r.target_id, r.edge_count)
+ for r in view.relations
+ if not r.target_id.startswith("ext:")
+ ]
+ assert in_view == internal
+
+
+async def test_container_dependencies_honour_exclusions(async_session):
+ import pathspec
+
+ repo = await _seed_monorepo(async_session)
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["packages/web/lib/"])
+ _, relations = await c4_builder.container_dependencies(
+ async_session, repo.id, exclude_spec=spec
+ )
+ assert relations == []
+
+
+async def test_overview_dependency_block_is_cached_and_empty_for_one_package(async_session):
+ from types import SimpleNamespace
+
+ from repowise.server.mcp_server.tool_overview.graph import (
+ _build_package_dependencies,
+ reset_cache,
+ )
+
+ reset_cache()
+ repo = await _seed_monorepo(async_session)
+ handle = SimpleNamespace(id=repo.id, head_commit="c1")
+ expected = {
+ "edges": [{"from": "packages/web", "to": "packages/core", "verb": "imports", "weight": 1}]
+ }
+ block = await _build_package_dependencies(async_session, handle)
+ assert block == expected
+
+ # Same index state: served from the cache, blind to a new edge. A new
+ # commit re-derives it.
+ await batch_upsert_graph_edges(
+ async_session,
+ repo.id,
+ [{"source_node_id": "packages/web/app/page.tsx", "target_node_id": "packages/core/ingestion/graph.py", "edge_type": "imports"}],
+ )
+ await async_session.commit()
+ block["edges"].clear()
+ assert await _build_package_dependencies(async_session, handle) == expected
+ moved = SimpleNamespace(id=repo.id, head_commit="c2")
+ assert (await _build_package_dependencies(async_session, moved))["edges"][0]["weight"] == 2
+
+ single = await upsert_repository(async_session, name="single", local_path="/tmp/single")
+ await batch_upsert_graph_nodes(
+ async_session,
+ single.id,
+ [
+ {"node_id": "pyproject.toml", "node_type": "file", "language": "toml", "symbol_count": 0},
+ {"node_id": "src/app.py", "node_type": "file", "language": "python", "symbol_count": 1},
+ {"node_id": "src/util.py", "node_type": "file", "language": "python", "symbol_count": 1},
+ ],
+ )
+ await batch_upsert_graph_edges(
+ async_session,
+ single.id,
+ [{"source_node_id": "src/app.py", "target_node_id": "src/util.py", "edge_type": "imports"}],
+ )
+ await async_session.commit()
+ single_handle = SimpleNamespace(id=single.id, head_commit="c1")
+ assert await _build_package_dependencies(async_session, single_handle) == {}