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
fix(mcp): stop treating co-change edges as dependencies (#1470)
Raghav Chamadiya890511cf6c72
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex dddc7777b..00e7f5538 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -272,19 +272,30 @@ EdgeType = Literal["type_use",]+# Structural containment, not reference. ``defines`` is file → symbol and+# ``has_method`` / ``has_property`` are class symbol → member symbol, so both+# endpoints describe the same code rather than one depending on the other.+# Their target is a ``path::Name`` symbol node, which is why a consumer that+# keys on file paths gets nothing usable out of them.+CONTAINMENT_EDGE_TYPES: frozenset[str] = frozenset({"defines", "has_method", "has_property"})++# Evidence from history rather than from code: two files move together in+# commits, not one referencing the other. This is the one that bites, because+# a co-change edge fed back in as a dependency makes every co-change partner+# look like an import of its own subject.+TEMPORAL_EDGE_TYPES: frozenset[str] = frozenset({"co_changes"})+# Edge types that are *not* code dependencies, and so must be excluded by any-# consumer answering "what depends on this?".+# consumer answering "what depends on this?" about FILES.#-# ``defines`` (file → symbol) and ``has_method`` / ``has_property``-# (class symbol → member symbol) are containment: a file "depends on" the-# symbols it declares only in a sense nobody asks about.-# ``co_changes`` is temporal: evidence that two files move together in history,-# not evidence that one references the other. It is also the one that bites,-# because a co-change edge fed back in as a dependency makes every co-change-# partner look like an import of its own subject.-NON_DEPENDENCY_EDGE_TYPES: frozenset[str] = frozenset(- {"defines", "has_method", "has_property", "co_changes"}-)+# Excluding containment is right for that question and wrong for traversal.+# Containment is the only bridge between the two layers of the graph: files are+# joined to each other by ``imports`` / ``type_use``, symbols to each other by+# ``calls`` / ``extends`` / ``implements``, and nothing points from a symbol+# back to a file. Drop ``defines`` and a caller can no longer walk from a file+# to the functions it declares, so anything traversing the graph wants+# ``TEMPORAL_EDGE_TYPES`` and a ``node_type`` check instead.+NON_DEPENDENCY_EDGE_TYPES: frozenset[str] = CONTAINMENT_EDGE_TYPES | TEMPORAL_EDGE_TYPES@dataclassdiff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex a6863b1e6..10118adff 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -27,11 +27,13 @@ Pipeline (each stage is a pure function over hit dicts):peripheral ones at similar retrieval score.This is what rescues "how does X work"questions from peripheral consumers of X.- 4. ``expand_via_graph`` — for top-N hits, walk 1 hop through imports+ 4. ``expand_via_graph`` — for top-N hits, walk 1 hop through the graphand pull in neighbors that have a wikipage. Rescues near-misses where retrievallanded in the right module but on a wrong- file (consumer vs. orchestrator).+ file (consumer vs. orchestrator). Reference+ and co-change edges both qualify; see the+ note on the queries for why.Stages downstream of this module (term coverage, intersection boost, domainpenalty) live in ``tool_answer`` for now — they're tightly coupled to the@@ -51,6 +53,7 @@ from typing import Anyfrom sqlalchemy import func, selectfrom repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX+from repowise.core.ingestion.models import CONTAINMENT_EDGE_TYPESfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphEdge, GraphNode, Pagefrom repowise.core.providers.embedding import store_has_semantic_vectors@@ -718,7 +721,18 @@ async def _neighbor_degrees(session: Any, nodes: set[str]) -> dict[str, int]:degree: dict[str, int] = {}for column in (GraphEdge.source_node_id, GraphEdge.target_node_id):res = await session.execute(- select(column, func.count()).where(column.in_(nodes)).group_by(column)+ select(column, func.count())+ .where(+ column.in_(nodes),+ # Count over the same edges the walk above traverses. Counting+ # containment too inflates a file's degree by the number of+ # symbols it declares, so a symbol-rich file reads as a hub on+ # its own size, and the p99 cutoff moves with how many symbol+ # nodes happen to be in the candidate set rather than with how+ # connected the files are.+ GraphEdge.edge_type.notin_(CONTAINMENT_EDGE_TYPES),+ )+ .group_by(column))for node_id, count in res.all():degree[node_id] = degree.get(node_id, 0) + int(count or 0)@@ -761,25 +775,37 @@ async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:existing = {h.get("target_path") for h in hits}async with get_session(ctx.session_factory) as session:- # Importers (someone → seed) and importees (seed → someone) in one- # query each. Two queries are fine — both hit the same indexed edge- # table and run in <10ms on the corpus this is tuned for.- importer_res = await session.execute(- select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ # Inbound (someone → seed) and outbound (seed → someone) in one query+ # each. Two queries are fine — both hit the same indexed edge table and+ # run in <10ms on the corpus this is tuned for.+ #+ # Not import edges only, despite the naming this code used to carry:+ # ``co_changes`` neighbours stay in on purpose, because "this file+ # moves with yours" is a genuine read-this-too signal, and expansion+ # surfaces what it adds neutrally as ``[graph-expanded]`` rather than+ # as an import claim. Containment edges are excluded because they can+ # never contribute: their endpoint is a ``path::Name`` symbol node, and+ # the page lookup below matches ``target_path`` against ``file_page``+ # rows, so every such neighbour was fetched only to be discarded.+ neighbor_cols = (GraphEdge.source_node_id, GraphEdge.target_node_id)+ inbound_res = await session.execute(+ select(*neighbor_cols).where(GraphEdge.target_node_id.in_(seed_paths),+ GraphEdge.edge_type.notin_(CONTAINMENT_EDGE_TYPES),))- importee_res = await session.execute(- select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ outbound_res = await session.execute(+ select(*neighbor_cols).where(GraphEdge.source_node_id.in_(seed_paths),+ GraphEdge.edge_type.notin_(CONTAINMENT_EDGE_TYPES),))neighbors: set[str] = set()- for src, _tgt in importer_res.all():+ for src, _tgt in inbound_res.all():if src and src not in existing:neighbors.add(src)- for _src, tgt in importee_res.all():+ for _src, tgt in outbound_res.all():if tgt and tgt not in existing:neighbors.add(tgt)diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex ebbda7737..90c1cad70 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -18,6 +18,7 @@ from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.generation.page_selection import STALE_STATUSES+from repowise.core.ingestion.models import NON_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.crud import get_kg_layers, get_kg_tour_stepsfrom repowise.core.persistence.decision_graph import get_governing_decisionsfrom repowise.core.persistence.models import (@@ -653,11 +654,15 @@ async def _resolve_one_target(# is empty, synthesize a deterministic one-liner from structure.if not docs.get("summary"):docs["summary"] = _synthesize_structural_summary(target, classes, functions)- # Importers+ # Importers. The key is literally ``imported_by``, so the scan+ # has to exclude the edge types that are not references —+ # otherwise a file that merely tends to change alongside this+ # one is served to the agent as one of its importers.res = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id,GraphEdge.target_node_id == target,+ GraphEdge.edge_type.notin_(NON_DEPENDENCY_EDGE_TYPES),))importers = res.scalars().all()@@ -782,11 +787,12 @@ async def _resolve_one_target(docs["file_summary"] = sym_page.summary or ""if want_full_doc:docs["documentation"] = sym_page.content- # Used by+ # Used by — same requirement as ``imported_by`` above.res = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id,GraphEdge.target_node_id == sym.file_path,+ GraphEdge.edge_type.notin_(NON_DEPENDENCY_EDGE_TYPES),))edges = res.scalars().all()diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex a26164f20..0adbcd98e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -7,6 +7,7 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPESfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -48,9 +49,20 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)+ # Drop the temporal relation only. A ``co_changes`` edge records that+ # two files move together in history, so leaving it in makes it a free+ # hop and the tool reports a "dependency path" no code creates.+ #+ # Containment stays, unlike in the consumers that answer "what depends+ # on this file". ``defines`` is the only bridge from the file layer to+ # the symbol layer, and no edge points back the other way, so excluding+ # it cannot suppress a false file-to-file path — there is none to+ # suppress — while it does delete the real ones: a --defines--> a::foo+ # --calls--> b::bar is how a caller asks which file reaches a function.edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repository.id,+ GraphEdge.edge_type.notin_(TEMPORAL_EDGE_TYPES),))edges = edge_result.scalars().all()@@ -75,6 +87,12 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)# ancestors, shared neighbors, and bridges never route through excluded files.allowed = {n.node_id for n in nodes} if exclude_spec else Nonegraph = nx.DiGraph()+ # Seed every surviving node, not just the endpoints of surviving edges. A+ # file whose only edges were temporal is still indexed, and the "no direct+ # path" branch below has a co-change fallback written precisely for it —+ # unreachable if the node never entered the graph, which also made the+ # "not found in graph" message untrue.+ graph.add_nodes_from(n.node_id for n in nodes)for e in edges:if allowed is not None and (e.source_node_id not in allowed or e.target_node_id not in alloweddiff --git a/tests/unit/server/mcp/test_answer_graph_expand_edges.py b/tests/unit/server/mcp/test_answer_graph_expand_edges.pynew file mode 100644index 000000000..eab6c28a1--- /dev/null+++ b/tests/unit/server/mcp/test_answer_graph_expand_edges.py@@ -0,0 +1,126 @@+"""Which edge types ``expand_via_graph`` may walk.++This is a guard on a deliberate asymmetry, not a regression test for a fix.++``expand_via_graph`` is retrieval rescue: it folds one-hop graph neighbours of+the top candidates back into the hit list so a question about a wrapper can+still reach the implementation. It used to call its two queries "importers"+and "importees" while filtering on no edge type at all, which invited a+follow-up to make the code match the comment by excluding every+``NON_DEPENDENCY_EDGE_TYPES`` value.++Doing that would be wrong here. Unlike ``get_risk`` — which states an import+relationship and so must not count a co-change as one — expansion only claims+"read this too", and surfaces what it adds neutrally as ``[graph-expanded]``.+A file that historically moves with the seed is a good answer to that. So+co-change neighbours stay, and only containment edges are excluded.+"""++from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace++import pytest++from repowise.core.persistence.models import GraphEdge, GraphNode, Page++_SEED = "src/auth/service.py"+_PARTNER = "src/reports/exporter.py"+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)+++async def _seed_co_change_partner_with_a_page(factory, repo_id: str) -> None:+ async with factory() as s:+ s.add(+ GraphNode(+ id="gn-partner",+ repository_id=repo_id,+ node_id=_PARTNER,+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=False,+ pagerank=0.3,+ betweenness=0.0,+ community_id=3,+ created_at=_NOW,+ )+ )+ s.add(+ GraphEdge(+ id="ge-cochange-expand",+ repository_id=repo_id,+ source_node_id=_SEED,+ target_node_id=_PARTNER,+ imported_names_json="[]",+ edge_type="co_changes",+ created_at=_NOW,+ )+ )+ s.add(+ Page(+ id=f"file_page:{_PARTNER}",+ repository_id=repo_id,+ page_type="file_page",+ title=f"File: {_PARTNER}",+ content="# exporter\n\nWrites the report bundle.",+ summary="Writes the report bundle.",+ target_path=_PARTNER,+ source_hash="exp1",+ model_name="mock",+ provider_name="mock",+ generation_level=4,+ created_at=_NOW,+ updated_at=_NOW,+ )+ )+ await s.commit()+++async def test_co_change_neighbour_is_still_expanded(setup_mcp, factory):+ from repowise.server.mcp_server._answer_pipeline import expand_via_graph++ await _seed_co_change_partner_with_a_page(factory, setup_mcp)++ hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory))++ added = {h["target_path"] for h in expanded if h.get("_expanded_from") == "graph"}+ assert _PARTNER in added, (+ "co-change neighbours are retained on purpose; excluding every "+ "NON_DEPENDENCY_EDGE_TYPES value here would silently narrow recall"+ )+++async def test_containment_neighbours_are_excluded(setup_mcp, factory):+ """The half of the filter that IS a change.++ Containment endpoints are ``path::Name`` symbol nodes, so they could never+ match a ``file_page`` and were fetched only to be discarded. They also fed+ the neighbour set that sizes the hub cutoff, which is why dropping them is+ not merely a saving — see ``_neighbor_degrees``.+ """+ from repowise.server.mcp_server._answer_pipeline import expand_via_graph++ symbol_id = f"{_SEED}::AuthService"+ async with factory() as s:+ s.add(+ GraphEdge(+ id="ge-defines-expand",+ repository_id=setup_mcp,+ source_node_id=_SEED,+ target_node_id=symbol_id,+ imported_names_json="[]",+ edge_type="defines",+ created_at=_NOW,+ )+ )+ await s.commit()++ hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory))++ assert symbol_id not in {h.get("target_path") for h in expanded}diff --git a/tests/unit/server/mcp/test_context_imported_by_edges.py b/tests/unit/server/mcp/test_context_imported_by_edges.pynew file mode 100644index 000000000..70980fbe3--- /dev/null+++ b/tests/unit/server/mcp/test_context_imported_by_edges.py@@ -0,0 +1,52 @@+"""``get_context`` must not serve non-reference edges under ``imported_by``.++Two scans in ``tool_context/targets.py`` collected every inbound ``graph_edges``+row for a target and published the sources as ``imported_by`` (file target) and+``used_by`` (symbol target). Both keys name a code reference, so a co-change+partner arriving there tells the agent that a file imports another when nothing+in the source says so.++This is the same defect as the ``get_risk`` filter, in a default-on tool.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest++from repowise.core.persistence.models import GraphEdge++_TARGET = "src/auth/service.py"+_PARTNER = "src/reports/exporter.py"+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)+++async def _add_inbound_co_change(factory, repo_id: str) -> None:+ async with factory() as s:+ s.add(+ GraphEdge(+ id="ge-cochange-context",+ repository_id=repo_id,+ source_node_id=_PARTNER,+ target_node_id=_TARGET,+ imported_names_json="[]",+ edge_type="co_changes",+ created_at=_NOW,+ )+ )+ await s.commit()+++async def test_co_change_partner_is_not_an_importer(setup_mcp, factory):+ from repowise.server.mcp_server import get_context++ await _add_inbound_co_change(factory, setup_mcp)++ result = await get_context(targets=[_TARGET], compact=False)+ imported_by = result["targets"][_TARGET]["docs"]["imported_by"]++ assert _PARTNER not in imported_by, "a co-change partner was published as an importer"+ # The real importer survives, so the filter has not blanked the field.+ assert "src/auth/middleware.py" in imported_bydiff --git a/tests/unit/server/mcp/test_dependency_path_edges.py b/tests/unit/server/mcp/test_dependency_path_edges.pynew file mode 100644index 000000000..303565fad--- /dev/null+++ b/tests/unit/server/mcp/test_dependency_path_edges.py@@ -0,0 +1,156 @@+"""``get_dependency_path`` must walk dependency edges only.++The tool loaded every ``graph_edges`` row for the repository into a NetworkX+graph and reported the shortest path through it. The table also carries the+temporal ``co_changes`` relation and file-to-symbol containment, so a+co-change edge was a free hop: the tool would answer "these two files are+connected" and name a path that no import, call or type reference creates.++Same root cause as the ``get_risk`` filter in ``test_risk_dependency_edges``.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest++from repowise.core.persistence.models import GraphEdge, GraphNode++_ORPHAN = "src/reports/exporter.py"+_TARGET = "src/db/models.py"+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)+++async def _add_co_change_only_neighbour(factory, repo_id: str) -> None:+ """A file with no code link to the graph, joined only by co-change."""+ async with factory() as s:+ s.add(+ GraphNode(+ id="gn-orphan",+ repository_id=repo_id,+ node_id=_ORPHAN,+ node_type="file",+ language="python",+ symbol_count=1,+ is_entry_point=False,+ pagerank=0.05,+ betweenness=0.0,+ community_id=3,+ created_at=_NOW,+ )+ )+ s.add(+ GraphEdge(+ id="ge-cochange-path",+ repository_id=repo_id,+ source_node_id=_ORPHAN,+ target_node_id=_TARGET,+ imported_names_json="[]",+ edge_type="co_changes",+ created_at=_NOW,+ )+ )+ await s.commit()+++async def test_co_change_edge_is_not_a_dependency_path(setup_mcp, factory):+ from repowise.server.mcp_server import get_dependency_path++ await _add_co_change_only_neighbour(factory, setup_mcp)++ result = await get_dependency_path(_ORPHAN, _TARGET)++ assert result.get("path") in (None, []), (+ f"co_changes edge was walked as a dependency: {result.get('path')}"+ )+ # Shortest-path must be what rejected the hop. If the node had instead+ # fallen out of the graph, this would pass while silently killing the+ # no-path fallbacks below — which is exactly how an earlier version of+ # this test passed for the wrong reason.+ assert "not found in graph" not in (result.get("explanation") or "")+++async def test_a_node_with_only_temporal_edges_still_reaches_the_fallbacks(+ setup_mcp, factory+):+ """Filtering edges must not delete nodes.++ The graph is built from edge endpoints, so a file whose only edges were+ temporal used to vanish and return "not found in graph" — skipping the+ no-path branch that carries ``visual_context`` and the ``co_change_signal``+ written for precisely this case.+ """+ from repowise.server.mcp_server import get_dependency_path++ await _add_co_change_only_neighbour(factory, setup_mcp)++ result = await get_dependency_path(_ORPHAN, _TARGET)++ assert "not found in graph" not in (result.get("explanation") or "")+ assert result.get("visual_context") is not None+++async def test_a_path_through_the_symbol_layer_still_resolves(setup_mcp, factory):+ """``defines`` is the only bridge from a file to its symbols.++ Nothing points from a symbol back to a file, so excluding containment can+ never suppress a false file-to-file path. It only deletes the real+ file → symbol → symbol answer to "which file reaches this function".+ """+ from repowise.server.mcp_server import get_dependency_path++ async with factory() as s:+ s.add(+ GraphNode(+ id="gn-sym",+ repository_id=setup_mcp,+ node_id="src/db/models.py::User",+ node_type="symbol",+ language="python",+ symbol_count=0,+ is_entry_point=False,+ pagerank=0.1,+ betweenness=0.0,+ community_id=2,+ created_at=_NOW,+ )+ )+ s.add(+ GraphEdge(+ id="ge-defines-path",+ repository_id=setup_mcp,+ source_node_id=_TARGET,+ target_node_id="src/db/models.py::User",+ imported_names_json="[]",+ edge_type="defines",+ created_at=_NOW,+ )+ )+ await s.commit()++ result = await get_dependency_path(_TARGET, "src/db/models.py::User")++ assert [hop["node"] for hop in result.get("path") or []] == [+ _TARGET,+ "src/db/models.py::User",+ ]+++async def test_real_import_path_still_resolves(setup_mcp, factory):+ """The filter must not empty the graph — the seeded import chain stands."""+ from repowise.server.mcp_server import get_dependency_path++ await _add_co_change_only_neighbour(factory, setup_mcp)++ result = await get_dependency_path("src/auth/middleware.py", _TARGET)++ assert [hop["node"] for hop in result.get("path") or []] == [+ "src/auth/middleware.py",+ "src/auth/service.py",+ _TARGET,+ ]