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.

fix(mcp): let get_answer expansion see the call graph (#1829)

Raghav Chamadiya870e042577fd
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
index 1aad1772c..0bdf3bb82 100644
--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py
@@ -50,7 +50,7 @@ import re
from collections import OrderedDict
from typing import Any
-from sqlalchemy import func, select
+from sqlalchemy import select
from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX
from repowise.core.ingestion.models import CONTAINMENT_EDGE_TYPES
@@ -58,6 +58,11 @@ from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GraphEdge, GraphNode, Page
from repowise.core.providers.embedding import store_has_semantic_vectors
from repowise.core.test_paths import is_test_path
+from repowise.server.mcp_server._graph_files import (
+ is_symbol_node,
+ keep_projected_edge,
+ node_to_file,
+)
from repowise.server.mcp_server._helpers import (
_VECTOR_TIMEOUT_ENV,
vector_search_timeout_s,
@@ -719,34 +724,53 @@ async def apply_pagerank_bias(hits: list[dict], ctx: Any) -> None:
# ---------------------------------------------------------------------------
-async def _neighbor_degrees(session: Any, nodes: set[str]) -> dict[str, int]:
- """Total graph degree (in + out) for each node in *nodes*.
+def _projected_pair(
+ src: str | None, tgt: str | None, edge_type: str | None, confidence: float | None
+) -> tuple[str | None, str | None]:
+ """An edge's two endpoints as file paths, or ``(None, None)`` to drop it.
- One grouped count per direction over the same indexed edge table the
- expansion already reads, scoped to the candidate set rather than the whole
- graph.
+ Only the symbol layer gets the guards; the file layer is already
+ file-to-file and keeps today's behaviour. The asymmetry is deliberate — the
+ guards refuse cross-extension pairs, and a ``co_changes`` edge between a
+ module and its docs is a "read this too" expansion has always served.
"""
- if not nodes:
- return {}
- 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),
- # 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)
+ src = src or ""
+ tgt = tgt or ""
+ if not is_symbol_node(src) and not is_symbol_node(tgt):
+ return (src or None, tgt or None)
+ src_file, tgt_file = node_to_file(src), node_to_file(tgt)
+ if not keep_projected_edge(src_file, tgt_file, edge_type, confidence):
+ return (None, None)
+ return (src_file, tgt_file)
+
+
+async def _projected_edges(session: Any, repo_id: str) -> list[tuple[str, str]]:
+ """Every non-containment edge for *repo_id*, as a pair of file paths.
+
+ One scan, projected in Python. A prefix match on the symbol layer cannot use
+ the node-id index (SQLite disables the LIKE optimisation under an ESCAPE
+ clause), so per-candidate queries were a scan each; this is one.
+
+ Containment is excluded because both its endpoints describe the same file,
+ so a projected containment edge is always a self-loop.
+ """
+ res = await session.execute(
+ select(
+ GraphEdge.source_node_id,
+ GraphEdge.target_node_id,
+ GraphEdge.edge_type,
+ GraphEdge.confidence,
+ ).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type.notin_(CONTAINMENT_EDGE_TYPES),
)
- for node_id, count in res.all():
- degree[node_id] = degree.get(node_id, 0) + int(count or 0)
- return degree
+ )
+ pairs: list[tuple[str, str]] = []
+ for src, tgt, etype, conf in res.all():
+ src_file, tgt_file = _projected_pair(src, tgt, etype, conf)
+ if src_file and tgt_file:
+ pairs.append((src_file, tgt_file))
+ return pairs
def _hub_degree_cutoff(degree: dict[str, int]) -> int:
@@ -763,7 +787,7 @@ def _hub_degree_cutoff(degree: dict[str, int]) -> int:
return max(_HUB_DEGREE_FLOOR, values[idx])
-async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:
+async def expand_via_graph(hits: list[dict], ctx: Any, repo_id: str) -> list[dict]:
"""Add up to ``_GRAPH_EXPAND_MAX_NEW`` graph-neighbor files to ``hits``.
Rescues near-misses where the top retrieved file is in the right
@@ -785,39 +809,26 @@ 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:
- # 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),
- )
- )
- outbound_res = await session.execute(
- select(*neighbor_cols).where(
- GraphEdge.source_node_id.in_(seed_paths),
- GraphEdge.edge_type.notin_(CONTAINMENT_EDGE_TYPES),
- )
- )
+ # ``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.
+ #
+ # The scan reaches the symbol layer as well as the file layer: ``calls``
+ # and its siblings join ``path::Name`` nodes, so an equality test against
+ # a seed path matched none of them and the call graph was invisible here.
+ seed_set = set(seed_paths)
+ pairs = await _projected_edges(session, repo_id)
neighbors: set[str] = set()
- for src, _tgt in inbound_res.all():
- if src and src not in existing:
- neighbors.add(src)
- for _src, tgt in outbound_res.all():
- if tgt and tgt not in existing:
- neighbors.add(tgt)
+ degree: dict[str, int] = {}
+ for src_file, tgt_file in pairs:
+ degree[src_file] = degree.get(src_file, 0) + 1
+ degree[tgt_file] = degree.get(tgt_file, 0) + 1
+ for mine, theirs in ((src_file, tgt_file), (tgt_file, src_file)):
+ if mine in seed_set and theirs not in existing:
+ neighbors.add(theirs)
if not neighbors:
return hits
@@ -826,7 +837,7 @@ async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:
# context block can't carry a useful excerpt for them.
page_res = await session.execute(
select(Page.target_path, Page.summary, Page.page_type).where(
- Page.target_path.in_(neighbors),
+ Page.target_path.in_(sorted(neighbors)),
Page.page_type == "file_page",
)
)
@@ -835,12 +846,11 @@ async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:
# Also load PageRank for the neighbors so we can rank them.
pr_res = await session.execute(
select(GraphNode.node_id, GraphNode.pagerank).where(
- GraphNode.node_id.in_(neighbors),
+ GraphNode.node_id.in_(sorted(neighbors)),
GraphNode.node_type == "file",
)
)
pr_by_path = {row[0]: float(row[1] or 0.0) for row in pr_res.all()}
- degree = await _neighbor_degrees(session, neighbors)
if not page_rows:
return hits
@@ -849,7 +859,9 @@ async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:
# them, which is the wrong instinct here: expansion is trying to name the
# specific file the question is about, and the most-imported file in the
# repo is the least specific candidate available.
- cutoff = _hub_degree_cutoff(degree)
+ # Scoped to the candidate set, not the repo: the cutoff answers "is this
+ # neighbour a hub among the ones on offer".
+ cutoff = _hub_degree_cutoff({row[0]: degree.get(row[0], 0) for row in page_rows})
non_hub = [row for row in page_rows if degree.get(row[0], 0) <= cutoff]
if non_hub:
page_rows = non_hub
@@ -877,7 +889,9 @@ async def expand_via_graph(hits: list[dict], ctx: Any) -> list[dict]:
# Rank candidates by PageRank within the expansion set so we pick the
# most central neighbor first when we have multiple plausible ones.
- candidates.sort(key=lambda c: -c.get("_pagerank", 0.0))
+ # Path breaks ties, so which neighbour is picked cannot move with the
+ # database's row order between runs on identical data.
+ candidates.sort(key=lambda c: (-c.get("_pagerank", 0.0), c["target_path"]))
additions = candidates[:_GRAPH_EXPAND_MAX_NEW]
if not additions:
return hits
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py
index 6f6e0438b..41a8f34d6 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py
@@ -8,29 +8,21 @@ every drop recoverable, and (b) a skeleton-stripping stage for the
``include=["skeleton"]`` blocks that did not exist when the original was
written.
-The MCP host caps the size of a tool result. Measured on Claude Code
-2026-07-11: a result whose stringified form exceeds ``MAX_MCP_OUTPUT_TOKENS``
-(default **25000 tokens**) is REJECTED with an isError
-(``MCPContentTooLargeError`` — "response (N tokens) exceeds maximum allowed
-tokens (25000)"), not silently truncated and not spilled to a file. That
-isError matters twice over: the agent loses the answer AND — per the Phase 1
-session-survival doctrine — one isError early in a session teaches it to
-abandon the server entirely. So staying under the host cap is not a nicety.
-
-Our default budget (``TOKEN_BUDGET`` = 8000) sits comfortably under the
-default host cap, so the common case is unchanged. The risk is the inverse of
-the one long assumed here: a user who *lowers* ``MAX_MCP_OUTPUT_TOKENS`` below
-our budget would start tripping the reject path. :func:`effective_char_budget`
-therefore reads the host cap at call time and clamps our ceiling under it.
-(The earlier "~10k token" ceiling in this docstring was a guess; the measured
-number is 25000, and the failure mode is rejection, not file spill.)
+The MCP host caps the size of a tool result. An over-cap result is **spilled to
+a sidecar file** the agent must Read back, not rejected: it comes back worded as
+an error but carries no ``isError``. The cap is counted in tokens; the spill
+message reports characters.
+
+Observed bounds: the largest MCP result that did NOT spill was 47,276 chars,
+the smallest that DID was 60,718 — consistent with a 25000-token cap at the
+~2.0-2.4 chars/token dense JSON really costs. ``CHAR_BUDGET`` (32,000) is about
+half that line. The residual risk is a user who *lowers*
+``MAX_MCP_OUTPUT_TOKENS``, which :func:`effective_char_budget` clamps for.
The estimator is intentionally dependency-free: 4 chars/token is the
-widely-quoted average for English + code on BPE tokenizers and is within
-~20% of tiktoken for typical wiki content. Dense code can tokenize finer than
-4 chars/token, so the host may count MORE tokens than we estimate — the
-safety fraction below absorbs that gap plus the JSON envelope and ``_meta``
-the host counts on top of our payload.
+widely-quoted average for English + code on BPE tokenizers, and it undercounts
+the compact JSON we emit by roughly 1.7x. ``HOST_CAP_BUDGET_FRACTION`` absorbs
+that gap plus the JSON envelope and ``_meta`` the host counts on top.
"""
from __future__ import annotations
@@ -48,14 +40,14 @@ TOKEN_BUDGET = 8000
CHARS_PER_TOKEN = 4
CHAR_BUDGET = TOKEN_BUDGET * CHARS_PER_TOKEN
-# Claude Code's MAX_MCP_OUTPUT_TOKENS default (measured 2026-07-11). A result
-# over this is rejected with an isError, so our ceiling must stay under it.
+# Claude Code's MAX_MCP_OUTPUT_TOKENS default. A result over this is spilled to
+# a sidecar file the agent must Read back, so our ceiling stays under it.
HOST_MCP_TOKEN_CAP_DEFAULT = 25000
# Fraction of the host cap we allow ourselves. The gap absorbs (a) estimator
-# error — our 4-chars/token figure can undercount real tokens on dense code by
-# up to ~30% — and (b) the JSON envelope + _meta the host tokenizes on top of
-# our payload. 0.6 keeps even an undercounted response clear of the reject line.
+# error — 4 chars/token undercounts compact JSON by roughly 1.7x — and (b) the
+# JSON envelope + _meta the host tokenizes on top of our payload. 0.6 keeps even
+# an undercounted response clear of the spill line.
HOST_CAP_BUDGET_FRACTION = 0.6
@@ -81,8 +73,8 @@ def effective_char_budget(configured: int = CHAR_BUDGET) -> int:
"""``configured`` ceiling, lowered under the live host cap when that is tighter.
Default host cap (25000) leaves our 8000-token budget untouched; a narrowed
- ``MAX_MCP_OUTPUT_TOKENS`` pulls us down with it so we never trip the host's
- reject-with-isError path (one isError = server abandonment, Phase 1).
+ ``MAX_MCP_OUTPUT_TOKENS`` pulls us down with it so a response can never
+ reach the host's spill-to-file path and cost the agent a Read.
"""
host_char_ceiling = int(host_token_cap() * HOST_CAP_BUDGET_FRACTION) * CHARS_PER_TOKEN
return min(configured, host_char_ceiling)
@@ -161,7 +153,7 @@ def truncate_to_budget(
``char_budget`` defaults to :func:`effective_char_budget` — our configured
ceiling, clamped under the live MCP host cap so the response can never trip
- the host's reject-with-isError path. Pass an explicit value to override
+ the host's spill-to-file path. Pass an explicit value to override
(tests do; production callers should not).
Strategy (applied in order, stopping as soon as the budget is met):
diff --git a/packages/server/src/repowise/server/mcp_server/_code_rationale.py b/packages/server/src/repowise/server/mcp_server/_code_rationale.py
index 31a302002..7e63ab54a 100644
--- a/packages/server/src/repowise/server/mcp_server/_code_rationale.py
+++ b/packages/server/src/repowise/server/mcp_server/_code_rationale.py
@@ -118,6 +118,9 @@ _MAX_FILE_LINES = 8000
_MAX_BLOCK_LINES = 12
_MAX_BLOCK_CHARS = 800
_MAX_RESULTS = 6
+# Keep a block only if it scores at least this fraction of the best block's
+# score. Relative, not absolute: scores scale with how many terms a question has.
+_RELEVANCE_FLOOR_FRACTION = 0.5
_NEAR_LINE_WINDOW = 60
@@ -319,6 +322,13 @@ def mine_rationale(
scored = [t for t in scored if t[1] or t[2]]
scored.sort(key=lambda t: t[0], reverse=True)
+
+ # Relevance floor, relative to the best block: below half the top score a
+ # block cleared the >=2-term gate on generic vocabulary rather than on the
+ # question — an SVG edge-routing docstring on "edges"/"project"/"between".
+ if scored:
+ floor = scored[0][0] * _RELEVANCE_FLOOR_FRACTION
+ scored = [t for t in scored if t[0] >= floor]
return [entry for _, _, _, entry in scored[:max_results]]
diff --git a/packages/server/src/repowise/server/mcp_server/_flow_path.py b/packages/server/src/repowise/server/mcp_server/_flow_path.py
index 85f27c4be..b7366a7b3 100644
--- a/packages/server/src/repowise/server/mcp_server/_flow_path.py
+++ b/packages/server/src/repowise/server/mcp_server/_flow_path.py
@@ -40,6 +40,11 @@ from sqlalchemy import select
from repowise.core.persistence.models import GraphEdge, Page, WikiSymbol
from repowise.core.test_paths import is_test_related_path
+from repowise.server.mcp_server._graph_files import (
+ file_ext,
+ keep_projected_edge,
+ node_to_file,
+)
# Edge kinds that form the file-level dependency graph. ``imports`` is
# file-to-file already; ``calls`` is symbol-to-symbol and gets projected to
@@ -48,11 +53,6 @@ from repowise.core.test_paths import is_test_related_path
# out of the path search.
_FLOW_EDGE_TYPES = ("imports", "calls")
-# Confidence floor for ``calls`` edges. Imports are always 1.0; calls average
-# 0.90 but have a low-confidence tail (heuristic resolution). 0.5 keeps every
-# genuine call and drops the noise. Imports are never filtered.
-_FLOW_CALLS_CONF_FLOOR = 0.5
-
# Depth cap for the path search. Endpoints connect in 2-4 hops on the measured
# graph; past 4 a "path" is a coincidence, not a flow.
_FLOW_MAX_DEPTH = 4
@@ -94,12 +94,6 @@ def _basename_stem(path: str) -> str:
return stem.lower()
-def _ext(path: str) -> str:
- """Lower-case file extension (``retrieval.py`` -> ``py``), ``""`` if none."""
- base = os.path.basename(path)
- return base.rsplit(".", 1)[1].lower() if "." in base else ""
-
-
def _is_plumbing(path: str) -> bool:
"""Package glue and tests: legitimate import hops but never a flow endpoint.
@@ -229,18 +223,9 @@ async def _load_file_adjacency(session: Any, repo_id: str) -> dict[str, list[str
)
adj: dict[str, set[str]] = {}
for src, tgt, etype, conf in res.all():
- if etype == "calls":
- if (conf or 0.0) < _FLOW_CALLS_CONF_FLOOR:
- continue
- src = src.split("::", 1)[0]
- tgt = tgt.split("::", 1)[0]
- if not src or not tgt or src == tgt:
- continue
- # A flow the answer traverses is single-language: cross-extension edges
- # (a Python module and a same-named TypeScript re-export, a test that
- # imports both ends) are graph coincidences, not dependency flow. Keeping
- # them lets BFS stitch unrelated files across package boundaries.
- if _ext(src) != _ext(tgt):
+ src = node_to_file(src or "")
+ tgt = node_to_file(tgt or "")
+ if not keep_projected_edge(src, tgt, etype, conf):
continue
adj.setdefault(src, set()).add(tgt)
adj.setdefault(tgt, set()).add(src)
@@ -345,9 +330,9 @@ async def expand_via_flow_path(
# language (``symbols.ts`` for a ``symbols.py`` question) is not an endpoint.
# Dropping off-language anchors here keeps the pairwise BFS from stitching
# two coincidental cross-package matches of a generic token.
- primary_ext = _ext(top_hit) if top_hit else ""
+ primary_ext = file_ext(top_hit) if top_hit else ""
if primary_ext:
- anchors = {p: src for p, src in anchors.items() if _ext(p) == primary_ext}
+ anchors = {p: src for p, src in anchors.items() if file_ext(p) == primary_ext}
if len(anchors) < _FLOW_MIN_QUESTION_ANCHORS:
return hits, []
diff --git a/packages/server/src/repowise/server/mcp_server/_graph_files.py b/packages/server/src/repowise/server/mcp_server/_graph_files.py
new file mode 100644
index 000000000..7dea2467c
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_graph_files.py
@@ -0,0 +1,55 @@
+"""One answer to "which files is this file a graph neighbour of".
+
+``imports`` joins file paths; ``calls`` and its siblings join ``path::Name``
+symbol nodes, and nothing points from a symbol back to its file, so a consumer
+keyed on paths sees only the first layer until it projects the second.
+
+Projecting also manufactures a self-loop out of every intra-file call and
+stitches files across a language boundary, so the guards live here with it.
+"""
+
+from __future__ import annotations
+
+import os
+
+# Confidence floor for ``calls`` edges. Imports are always 1.0; calls average
+# 0.90 with a low-confidence tail from heuristic resolution. 0.5 keeps every
+# genuine call and drops the noise.
+CALLS_CONF_FLOOR = 0.5
+
+
+def is_symbol_node(node_id: str) -> bool:
+ """Whether *node_id* addresses a symbol rather than a file."""
+ return "::" in node_id
+
+
+def node_to_file(node_id: str) -> str:
+ """``a/b.py::Klass.meth`` -> ``a/b.py``. A file node id is returned unchanged."""
+ return node_id.split("::", 1)[0]
+
+
+def file_ext(path: str) -> str:
+ """Lower-case file extension (``retrieval.py`` -> ``py``), ``""`` if none."""
+ base = os.path.basename(path)
+ return base.rsplit(".", 1)[1].lower() if "." in base else ""
+
+
+def keep_projected_edge(
+ src_file: str, tgt_file: str, edge_type: str | None, confidence: float | None
+) -> bool:
+ """Whether a symbol edge projected onto its two files is a real relation.
+
+ Three guards, all load-bearing:
+
+ * a ``calls`` edge below :data:`CALLS_CONF_FLOOR` is heuristic noise;
+ * a self-loop is what the projection manufactures out of every intra-file
+ call, and those outnumber the cross-file ones;
+ * a cross-extension pair is a graph coincidence rather than dependency flow
+ (a Python module and a same-named TypeScript re-export, a test naming both
+ ends), and keeping them lets a walk stitch unrelated packages together.
+ """
+ if edge_type == "calls" and (confidence or 0.0) < CALLS_CONF_FLOOR:
+ return False
+ if not src_file or not tgt_file or src_file == tgt_file:
+ return False
+ return file_ext(src_file) == file_ext(tgt_file)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index 2e373509f..40b055280 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
@@ -257,7 +257,7 @@ async def _run_retrieval_pipeline(
# (consumer instead of orchestrator). Adds up to 3 neighbors with a
# damped score, then re-sorts.
with contextlib.suppress(Exception):
- hits = await _expand_via_graph(hits, ctx)
+ hits = await _expand_via_graph(hits, ctx, repo_id)
# Re-filter: graph expansion can pull excluded neighbors back in (before the
# cap, so an excluded neighbor can't occupy a top-5 slot).
hits = filter_dicts_by_key(hits, "target_path", exclude_spec)
diff --git a/tests/unit/server/mcp/test_answer_graph_expand_edges.py b/tests/unit/server/mcp/test_answer_graph_expand_edges.py
index eab6c28a1..ed1ac096e 100644
--- a/tests/unit/server/mcp/test_answer_graph_expand_edges.py
+++ b/tests/unit/server/mcp/test_answer_graph_expand_edges.py
@@ -85,7 +85,7 @@ async def test_co_change_neighbour_is_still_expanded(setup_mcp, factory):
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))
+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory), setup_mcp)
added = {h["target_path"] for h in expanded if h.get("_expanded_from") == "graph"}
assert _PARTNER in added, (
@@ -121,6 +121,100 @@ async def test_containment_neighbours_are_excluded(setup_mcp, factory):
await s.commit()
hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]
- expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory))
+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory), setup_mcp)
assert symbol_id not in {h.get("target_path") for h in expanded}
+
+
+async def _seed_callee_with_a_page(factory, repo_id: str, path: str, confidence: float) -> None:
+ """A ``calls`` edge from a symbol in ``_SEED`` to a symbol in *path*."""
+ async with factory() as s:
+ s.add(
+ GraphNode(
+ id=f"gn-{path}",
+ repository_id=repo_id,
+ node_id=path,
+ node_type="file",
+ language="python",
+ symbol_count=1,
+ is_entry_point=False,
+ pagerank=0.1,
+ betweenness=0.0,
+ community_id=4,
+ created_at=_NOW,
+ )
+ )
+ s.add(
+ GraphEdge(
+ id=f"ge-calls-{path}",
+ repository_id=repo_id,
+ source_node_id=f"{_SEED}::login",
+ target_node_id=f"{path}::verify",
+ imported_names_json="[]",
+ edge_type="calls",
+ confidence=confidence,
+ created_at=_NOW,
+ )
+ )
+ s.add(
+ Page(
+ id=f"file_page:{path}",
+ repository_id=repo_id,
+ page_type="file_page",
+ title=f"File: {path}",
+ content="# callee",
+ summary="The thing the seed calls.",
+ target_path=path,
+ source_hash=f"h-{path}",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=4,
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+ await s.commit()
+
+
+async def test_call_neighbour_is_expanded(setup_mcp, factory):
+ """``calls`` endpoints are ``path::Name`` nodes, so expansion only sees them
+ once they are projected onto their file."""
+ from repowise.server.mcp_server._answer_pipeline import expand_via_graph
+
+ callee = "src/auth/tokens.py"
+ await _seed_callee_with_a_page(factory, setup_mcp, callee, confidence=0.9)
+
+ hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]
+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory), setup_mcp)
+
+ added = {h["target_path"] for h in expanded if h.get("_expanded_from") == "graph"}
+ assert callee in added
+ assert f"{callee}::verify" not in {h.get("target_path") for h in expanded}
+
+
+async def test_low_confidence_call_neighbour_is_not_expanded(setup_mcp, factory):
+ """The projection travels with its guards; without them it adds noise."""
+ from repowise.server.mcp_server._answer_pipeline import expand_via_graph
+
+ callee = "src/auth/guessed.py"
+ await _seed_callee_with_a_page(factory, setup_mcp, callee, confidence=0.2)
+
+ hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]
+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory), setup_mcp)
+
+ assert callee not in {h["target_path"] for h in expanded if h.get("_expanded_from") == "graph"}
+
+
+async def test_cross_extension_call_neighbour_is_not_expanded(setup_mcp, factory):
+ from repowise.server.mcp_server._answer_pipeline import expand_via_graph
+
+ callee = "src/auth/tokens.ts"
+ await _seed_callee_with_a_page(factory, setup_mcp, callee, confidence=0.95)
+
+ hits = [{"target_path": _SEED, "score": 0.9, "page_type": "file_page"}]
+ expanded = await expand_via_graph(hits, SimpleNamespace(session_factory=factory), setup_mcp)
+
+ assert callee not in {h["target_path"] for h in expanded if h.get("_expanded_from") == "graph"}
diff --git a/tests/unit/server/mcp/test_code_rationale.py b/tests/unit/server/mcp/test_code_rationale.py
index 182d39eb8..11d170518 100644
--- a/tests/unit/server/mcp/test_code_rationale.py
+++ b/tests/unit/server/mcp/test_code_rationale.py
@@ -353,3 +353,24 @@ async def test_concept_anchor_skips_when_retrieval_already_led_with_winner(tmp_p
Path(str(repo)), "why is the caller list capped at 50", hits
)
assert all(not h.get("_concept_anchored") for h in out)
+
+
+def test_mine_drops_blocks_far_below_the_best_match(tmp_path):
+ """A block clearing the term gate on generic vocabulary is not rationale."""
+ _write(
+ tmp_path,
+ "strong.py",
+ "# We project each call edge onto its two files because the graph keeps\n"
+ "# symbols and files in separate layers.\nX = 1\n",
+ )
+ _write(
+ tmp_path,
+ "weak.py",
+ "# Edges bow outward so they never cross a box.\nY = 2\n",
+ )
+ query = "why project call edge endpoints onto files graph layers symbols"
+ out = mine_rationale(str(tmp_path), ["strong.py", "weak.py"], query)
+
+ paths = {r["path"] for r in out}
+ assert "strong.py" in paths
+ assert "weak.py" not in paths
diff --git a/tests/unit/server/mcp/test_graph_files.py b/tests/unit/server/mcp/test_graph_files.py
new file mode 100644
index 000000000..d1a27e38f
--- /dev/null
+++ b/tests/unit/server/mcp/test_graph_files.py
@@ -0,0 +1,31 @@
+"""The shared symbol-to-file projection and its guards."""
+
+from __future__ import annotations
+
+from repowise.server.mcp_server._graph_files import (
+ file_ext,
+ is_symbol_node,
+ keep_projected_edge,
+ node_to_file,
+)
+
+
+def test_node_to_file_projects_symbols_and_passes_files_through():
+ assert node_to_file("a/b.py::Klass.meth") == "a/b.py"
+ assert node_to_file("a/b.py") == "a/b.py"
+ assert is_symbol_node("a/b.py::X") and not is_symbol_node("a/b.py")
+
+
+def test_file_ext():
+ assert file_ext("a/b/retrieval.py") == "py"
+ assert file_ext("a/b/Makefile") == ""
+
+
+def test_guards():
+ assert keep_projected_edge("a.py", "b.py", "calls", 0.9)
+ # Below the floor, same file, and across a language boundary.
+ assert not keep_projected_edge("a.py", "b.py", "calls", 0.2)
+ assert not keep_projected_edge("a.py", "a.py", "calls", 0.9)
+ assert not keep_projected_edge("a.py", "b.ts", "calls", 0.9)
+ # The floor is scoped to ``calls``; nothing else carries a confidence tail.
+ assert keep_projected_edge("a.py", "b.py", "extends", 0.2)