Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(answer): show who uses the lead file on impact questions (#3212)
Raghav Chamadiyaf6c43dc5bab4
diff --git a/packages/server/src/repowise/server/mcp_server/_edit_sites.py b/packages/server/src/repowise/server/mcp_server/_edit_sites.pyindex 27b838b4a..b1fdf973c 100644--- a/packages/server/src/repowise/server/mcp_server/_edit_sites.py+++ b/packages/server/src/repowise/server/mcp_server/_edit_sites.py@@ -15,7 +15,7 @@ import jsonimport refrom collections import Counterfrom itertools import islice-from pathlib import Path+from pathlib import Path, PurePosixPathfrom typing import Anyfrom sqlalchemy import or_, select@@ -204,6 +204,69 @@ async def attach_call_text(rows[i].pop("call_line", None)+#: A runtime load: ``import(...)``, ``importlib.import_module(...)``, ``__import__(...)``.+_DYNAMIC_LOAD = re.compile(r"(?<![\w$.])(?:import|__import__)\s*\(|\bimport_module\s*\(")+#: Stems too common to name one file: the quoted path must also carry the parent.+_GENERIC_STEMS = frozenset(+ {"index", "utils", "util", "types", "main", "helpers", "constants", "config", "mod",+ "__init__"}+)+++def _module_spec(module_path: str) -> re.Pattern[str]:+ """A quoted module path ending in *module_path*'s stem, or its parent and stem when generic."""+ path = PurePosixPath(module_path)+ tail = re.escape(path.stem)+ if path.stem in _GENERIC_STEMS and path.parent.name:+ tail = rf"{re.escape(path.parent.name)}[/.]{tail}"+ return re.compile(rf"""["'`](?:[^"'`\n]*[/.])?{tail}(?:\.[A-Za-z]+)?["'`]""")+++def _import_sites(+ root: Path, files: list[str], module_path: str+) -> dict[str, tuple[int, str, bool]]:+ """``file -> (line, text, dynamic)`` for the quoted path naming *module_path*.++ A line that imports, exports or loads it wins over an earlier plain mention.+ """+ spec = _module_spec(module_path)+ out: dict[str, tuple[int, str, bool]] = {}+ for rel in files:+ lines = _read_lines(root, rel) or []+ mention: int | None = None+ statements: set[int] | None = None+ for n, text in enumerate(lines, 1):+ if not spec.search(text):+ continue+ if statements is None:+ statements = _import_lines(lines)+ # ``import(`` may sit alone on the line above a wrapped path.+ wrapped = n > 1 and lines[n - 2].rstrip().endswith("import(")+ if wrapped or n in statements or _DYNAMIC_LOAD.search(text):+ mention = n+ break+ mention = mention or n+ if mention is not None:+ text = lines[mention - 1]+ dynamic = bool(_DYNAMIC_LOAD.search(text)) or (+ mention > 1 and lines[mention - 2].rstrip().endswith("import(")+ )+ out[rel] = (mention, text.strip()[:MAX_TEXT_CHARS], dynamic)+ return out+++async def import_sites(+ repo_root: str | Path | None, files: list[str], module_path: str+) -> dict[str, tuple[int, str, bool]]:+ """Where each of *files* names *module_path* by a quoted path, and whether it loads it at runtime.++ Unquoted imports (a dotted Python ``from`` line) are not found; those files are absent.+ """+ if not repo_root or not files:+ return {}+ return await asyncio.to_thread(_import_sites, Path(repo_root).resolve(), files, module_path)++def _scan(root: Path,files: list[str],diff --git a/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.pyindex 7f57698c1..0ddfa5494 100644--- a/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py+++ b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py@@ -62,7 +62,7 @@ def _is_wrapper(node: GraphNode, target: GraphNode, callees: set[str]) -> bool:)-def _imported_names(edge: GraphEdge) -> list[str]:+def imported_names(edge: GraphEdge) -> list[str]:try:names = json.loads(edge.imported_names_json or "[]")except (TypeError, ValueError):@@ -214,7 +214,7 @@ async def files_importing(importer = edge.source_node_idif importer in seen:continue- names = _imported_names(edge)+ names = imported_names(edge)candidates = by_file[edge.target_node_id]node = next((n for n in candidates if n.name in names), None)named = node is not Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex b0d127f9f..0586d7e56 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@@ -49,6 +49,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import functoolsimport json as _json # noqa: F401 — re-exported: a test patches answer._json.dumpsimport loggingimport time@@ -129,6 +130,7 @@ from repowise.server.mcp_server.tool_answer.callers import (caller_evidence,caller_lines,is_caller_question,+ is_impact_question,)from repowise.server.mcp_server.tool_answer.confidence import (_agreement_dominant,@@ -162,6 +164,11 @@ from repowise.server.mcp_server.tool_answer.evidence import (_is_readable_path,_repo_root,)+from repowise.server.mcp_server.tool_answer.neighbors import (+ attach_graph_neighbors,+ lead_file,+ neighbor_evidence,+)from repowise.server.mcp_server.tool_answer.payload import (_apply_lean_high, # noqa: F401 — backward-compatible helper re-export_build_best_guesses, # noqa: F401 — re-exported: imported from here by tests@@ -214,6 +221,24 @@ if _MAX_CHARS_PER_HIT_EXCERPT < _GATED_EXCERPT_CHARS:)+async def _attach_neighbors(+ payload: dict, *, wanted: bool, ctx, repo_id: str, hits: list[dict], exclude_spec+) -> dict:+ """``graph_neighbors`` for the file *payload* leads with; a failed lookup leaves it as is."""+ if not wanted:+ return payload+ lead = lead_file(payload)+ try:+ async with get_session(ctx.session_factory) as session:+ rows = await neighbor_evidence(+ session, repo_id, lead, hits, exclude_spec, repo_root=_repo_root(ctx)+ )+ except Exception:+ _log.warning("get_answer: graph neighbor lookup failed", exc_info=True)+ return payload+ return attach_graph_neighbors(payload, rows, lead)++class _Retrieved(NamedTuple):"""What retrieval resolved, before any decision about how to answer.@@ -458,6 +483,17 @@ async def get_answer(except Exception:_log.warning("get_answer: graph caller lookup failed", exc_info=True)+ # Impact questions the caller lookup left unanswered get the users of the+ # file the answer leads with, once that file is known.+ _neighbors = functools.partial(+ _attach_neighbors,+ wanted=not graph_callers.rows and is_impact_question(question, question_ids),+ ctx=ctx,+ repo_id=repo_id,+ hits=hits,+ exclude_spec=exclude_spec,+ )+# Computed once, above the early returns (they rate retrieval too). The leg# status is read, not inferred from the capped `hits`; see _agreement_dominant.agreement_dominant = (@@ -501,7 +537,9 @@ async def get_answer(_retrieval_quality(hits, agreement_dominant),)if union_payload is not None:- return _with_candidates(attach_graph_callers(union_payload, graph_callers), resolved_pool)+ return _with_candidates(+ await _neighbors(attach_graph_callers(union_payload, graph_callers)), resolved_pool+ )fallback_targets = [h["target_path"]@@ -544,16 +582,18 @@ async def get_answer(if not always_synthesize and not dominant:return _with_candidates(- attach_graph_callers(- await build_abstain_payload(- question=question,- ctx=ctx,- hits=hits,- fallback_targets=fallback_targets,- repository=repository,- t0=t0,- ),- graph_callers,+ await _neighbors(+ attach_graph_callers(+ await build_abstain_payload(+ question=question,+ ctx=ctx,+ hits=hits,+ fallback_targets=fallback_targets,+ repository=repository,+ t0=t0,+ ),+ graph_callers,+ )),resolved_pool,)@@ -598,6 +638,7 @@ async def get_answer(resolved_pool=resolved_pool,graph_callers=graph_callers,)+ payload = await _neighbors(payload)degraded_legs = _degraded_legs(_retrieval_legs())if degraded_legs:payload.setdefault("_meta", {})["retrieval_degraded"] = degraded_legs@@ -698,6 +739,7 @@ async def get_answer()attach_graph_callers(payload, graph_callers)+ await _neighbors(payload)if flow_paths:payload["flow_path"] = [" -> ".join(p) for p in flow_paths[:2]]diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/callers.py b/packages/server/src/repowise/server/mcp_server/tool_answer/callers.pyindex 7df18727c..b727bb17f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/callers.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/callers.py@@ -53,6 +53,27 @@ _NAMED_CALLER_QUESTION = re.compile(re.IGNORECASE,)+#: Asks which file or function wires something up, or what must change, without+#: necessarily naming a symbol: "which non-test file dynamically loads it".+_IMPACT_SUBJECT = (+ r"\b(?:which|what)(?:\s+[\w-]+){0,3}?\s+(?:files?|modules?|functions?|methods?|"+ r"class(?:es)?|components?|services?|packages?|handlers?|callers?|scripts?|code)"+ r"\s+(?:\w+ly\s+)?"+)+_IMPACT_QUESTION = re.compile(+ _IMPACT_SUBJECT + r"(?:calls?|invokes?|triggers?|imports?|re-?exports?|"+ r"registers?|references?|depends?\s+on|dispatch(?:es)?|wires?|fires?|"+ r"subscribes?|persists?)\b"+ r"|\bmust\s+change\b|\bwould\s+need\s+(?:updating|to\s+change)\b",+ re.IGNORECASE,+)+#: "uses" and "loads" also describe style or speed ("which file uses tabs"), so+#: they count only with a code name or a pronoun object.+_WEAK_IMPACT_QUESTION = re.compile(+ _IMPACT_SUBJECT + r"(?:uses?|loads?)\b(?P<pronoun>\s+(?:it|this|that|them)\b)?",+ re.IGNORECASE,+)+_TARGET_KINDS = ("function", "method", "class")#: A name with more definitions than this is too generic to answer for._MAX_DEFS_PER_NAME = 4@@ -96,6 +117,14 @@ def is_caller_question(question: str, question_ids: set[str]) -> bool:return bool(_named_ids(question_ids)) and bool(_NAMED_CALLER_QUESTION.search(question))+def is_impact_question(question: str, question_ids: set[str]) -> bool:+ """A caller question, or one asking which code wires, loads or must change for something."""+ if is_caller_question(question, question_ids) or _IMPACT_QUESTION.search(question):+ return True+ weak = _WEAK_IMPACT_QUESTION.search(question)+ return bool(weak) and bool(weak.group("pronoun") or _named_ids(question_ids))++def _named_ids(question_ids: set[str]) -> list[str]:"""Code-shaped identifiers; a bare leaf yields to the qualified form naming it."""ids = {q for q in question_ids if _unmistakably_code(q)}@@ -173,7 +202,7 @@ async def _retrieved_targets(return sorted(res.scalars().all(), key=lambda n: (order.get(n.name, 99), n.node_id))-def _row(+def caller_row(caller: str,file: str,line: int | None,@@ -263,7 +292,7 @@ async def caller_evidence(seen.add(e.source_node_id)src = nodes.get(e.source_node_id)rows.append(- _row(+ caller_row(e.source_node_id,src.file_path if src else e.source_node_id.split("::")[0],src.start_line if src else None,@@ -280,7 +309,7 @@ async def caller_evidence(if caller in seen or (cross_file and h["file"] == target.file_path):continueseen.add(caller)- row = _row(+ row = caller_row(caller,h["file"],h.get("line"),@@ -340,7 +369,7 @@ async def _registering_files(# take the only slots.imported.sort(key=lambda t: is_test_path(t[0]))return [- _row(importer, importer, None, symbol_id, "imports")+ caller_row(importer, importer, None, symbol_id, "imports")for importer, _conf, symbol_id, _named in imported[:_MAX_IMPORTER_ROWS]]@@ -358,33 +387,33 @@ def attach_graph_callers(payload: dict, evidence: CallerEvidence) -> dict:return payload-def _short(symbol_id: str) -> str:+def short_id(symbol_id: str) -> str:return symbol_id.split("::")[-1] if "::" in symbol_id else symbol_iddef _phrase(row: dict) -> str:line = row.get("call_line") or row.get("line")where = f"{row['file']}:{line}" if line is not None else row["file"]- target = _short(row["target"])+ target = short_id(row["target"])wrapper = row.get("via_wrapper")# A same-named caller or wrapper would read "X calls X"; the file tells them apart.- if target in (_short(row["caller"]), _short(wrapper or "")):+ if target in (short_id(row["caller"]), short_id(wrapper or "")):target = f"{target} in {row['target'].split('::')[0]}"if row["edge_type"] == "imports":if wrapper and row.get("wholesale"):return (f"{row['file']} loads {wrapper.split('::')[0]} wholesale, whose "- f"{_short(wrapper)} wraps {target}"+ f"{short_id(wrapper)} wraps {target}")if wrapper:return (- f"{row['file']} imports wrapper {_short(wrapper)} "+ f"{row['file']} imports wrapper {short_id(wrapper)} "f"({wrapper.split('::')[0]}), which calls {target}")return f"{row['file']} imports {target}"if wrapper:- return f"{_short(row['caller'])} ({where}) calls {target} via wrapper {_short(wrapper)}"- return f"{_short(row['caller'])} ({where}) calls {target}"+ return f"{short_id(row['caller'])} ({where}) calls {target} via wrapper {short_id(wrapper)}"+ return f"{short_id(row['caller'])} ({where}) calls {target}"def caller_lines(rows: list[dict]) -> list[str]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.pyindex 7266a356c..d298e6b89 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py@@ -280,7 +280,8 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5# 18: rows carry ``candidate_files``, the ranked paths-only list.# 19: rows carry ``_candidate_file_facts``; low answers serve slim best_guesses rows.# 20: caller questions carry ``graph_callers`` and synthesise with them.-_ANSWER_SCHEMA_VERSION = 20+# 21: impact questions carry ``graph_neighbors``, the users of the lead file.+_ANSWER_SCHEMA_VERSION = 21# Above this a whole-file Read costs more than the answer, so the low-confidence# hint names a ranged Read or a skeleton instead.diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/neighbors.py b/packages/server/src/repowise/server/mcp_server/tool_answer/neighbors.pynew file mode 100644index 000000000..658073feb--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/neighbors.py@@ -0,0 +1,242 @@+"""Inbound users of the file an impact answer leads with.++Impact questions are mostly phrased by behaviour, so no named symbol resolves+and ``graph_callers`` stays empty. The file the answer leads with still has+users in the graph: callers of its symbols (and one hop past forwarding+wrappers), files importing it, and value references. They are served as+``graph_neighbors``, one row per user file, production first.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence.crud import get_graph_nodes_by_ids+from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.core.test_paths import is_test_path+from repowise.server.mcp_server._budget import cap_collection+from repowise.server.mcp_server._edit_sites import attach_call_text, first_call_line, import_sites+from repowise.server.mcp_server._helpers import filter_dicts_by_key+from repowise.server.mcp_server._wrapper_callers import (+ MIN_CALL_CONFIDENCE,+ forwarding_wrapper_callers,+ imported_names,+)+from repowise.server.mcp_server.tool_answer.callers import caller_row, short_id++#: Kinds of use, strongest first; a file using the lead several ways keeps its strongest row.+_USE_RANK = {"calls": 0, "dynamic_imports": 1, "references": 2, "imports": 3}+#: Inbound symbol edges read for one file, best confidence first, so a hub stays bounded.+_MAX_EDGES = 200+#: Question-relevant symbols read on their own first, so a hub's popular symbols+#: cannot crowd them out of the capped read.+_MAX_RELEVANT = 2+_MAX_RELEVANT_EDGES = 50+#: Symbols whose forwarding wrappers are followed one hop.+_MAX_FOCUS = 3+_MAX_ROWS = 8+++def lead_file(payload: dict) -> str | None:+ """The file the answer names first: its first citation, else the top guess or fallback."""+ for path in payload.get("citations") or []:+ if isinstance(path, str) and path:+ return path+ for guess in payload.get("best_guesses") or []:+ if isinstance(guess, dict) and guess.get("file"):+ return guess["file"]+ targets = payload.get("fallback_targets") or []+ return targets[0] if targets and isinstance(targets[0], str) else None+++def _relevance(hits: list[dict], lead: str) -> dict[str, float]:+ """Symbol name -> how many of the question's terms retrieval found in it."""+ hit = next((h for h in hits if h.get("target_path") == lead), {})+ return {s.get("name"): s.get("_relevance") or 0 for s in hit.get("symbols") or []}+++def _focus(symbols: dict[str, GraphNode], edges: list[GraphEdge], relevance: dict[str, float]):+ """The lead's symbols ranked by the question's terms, then by how many other files call them."""+ callers: dict[str, set[str]] = {}+ for e in edges:+ if e.edge_type == "calls":+ callers.setdefault(e.target_node_id, set()).add(e.source_node_id.split("::")[0])+ ranked = sorted(+ callers,+ key=lambda sid: (-relevance.get(symbols[sid].name, 0), -len(callers[sid]), sid),+ )+ return {sid: i for i, sid in enumerate(ranked)}+++async def _inbound(+ session: AsyncSession, repo_id: str, targets: list[str], limit: int+) -> list[GraphEdge]:+ """Calls and value references into *targets*, best confidence first."""+ if not targets:+ return []+ res = await session.execute(+ select(GraphEdge)+ .where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id.in_(targets),+ GraphEdge.edge_type.in_(("calls", "references")),+ GraphEdge.confidence >= MIN_CALL_CONFIDENCE,+ )+ .order_by(GraphEdge.confidence.desc(), GraphEdge.source_node_id)+ .limit(limit)+ )+ return list(res.scalars().all())+++async def neighbor_evidence(+ session: AsyncSession,+ repo_id: str,+ lead: str | None,+ hits: list[dict],+ exclude_spec: Any = None,+ repo_root: str | Path | None = None,+) -> list[dict]:+ """Rows for the files that call, import, load or reference *lead*, production first."""+ if not lead or is_test_path(lead):+ return []+ res = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "symbol",+ GraphNode.file_path == lead,+ )+ )+ symbols = {n.node_id: n for n in res.scalars().all()}+ relevance = _relevance(hits, lead)+ relevant = sorted(+ (sid for sid, n in symbols.items() if relevance.get(n.name, 0) > 0),+ key=lambda sid: (-relevance[symbols[sid].name], sid),+ )[:_MAX_RELEVANT]+ edges: list[GraphEdge] = []+ seen_edges: set[tuple[str, str, str]] = set()+ for targets, limit in ((relevant, _MAX_RELEVANT_EDGES), (list(symbols), _MAX_EDGES)):+ for e in await _inbound(session, repo_id, targets, limit):+ key = (e.source_node_id, e.target_node_id, e.edge_type)+ if key not in seen_edges and e.source_node_id.split("::")[0] != lead:+ seen_edges.add(key)+ edges.append(e)+ res = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id == lead,+ GraphEdge.edge_type.in_(("imports", "dynamic_imports")),+ )+ )+ file_edges = sorted(res.scalars().all(), key=lambda e: e.source_node_id)+ focus = _focus(symbols, edges, relevance)+ nodes = await get_graph_nodes_by_ids(session, repo_id, list({e.source_node_id for e in edges}))++ candidates: list[dict] = []+ for e in edges:+ src = nodes.get(e.source_node_id)+ candidates.append(+ caller_row(+ e.source_node_id,+ e.source_node_id.split("::")[0],+ src.start_line if src else None,+ e.target_node_id,+ e.edge_type,+ first_call_line(e.call_lines_json),+ )+ )+ for target_id in sorted(focus, key=focus.get)[:_MAX_FOCUS]:+ direct = [e.source_node_id for e in edges if e.target_node_id == target_id]+ for h in await forwarding_wrapper_callers(+ session, repo_id, symbols[target_id], direct, known_nodes=nodes+ ):+ if h["file"] == lead:+ continue+ row = caller_row(+ h.get("symbol_id") or h["file"],+ h["file"],+ h.get("line"),+ target_id,+ h.get("edge_type") or "imports",+ h.get("call_line"),+ )+ if h.get("wholesale"):+ row["wholesale"] = True+ row["via_wrapper"] = h["via_wrapper"]+ candidates.append(row)+ by_name = {n.name: n.node_id for n in symbols.values()}+ for e in file_edges:+ names = imported_names(e)+ named = next((by_name[n] for n in names if n in by_name), None)+ row = caller_row(e.source_node_id, e.source_node_id, None, named or lead, e.edge_type)+ if e.edge_type == "imports" and named is None and "*" in names:+ row["wholesale"] = True+ candidates.append(row)++ for row in candidates:+ if is_test_path(row["file"]):+ row["test"] = True+ candidates = filter_dicts_by_key(candidates, "file", exclude_spec)++ def _rank(row: dict) -> tuple:+ return (+ bool(row.get("test")),+ _USE_RANK.get(row["edge_type"], len(_USE_RANK)),+ "via_wrapper" in row,+ bool(row.get("wholesale")),+ focus.get(row["target"], len(focus)),+ )++ rows: list[dict] = []+ seen: set[str] = set()+ for row in sorted(candidates, key=_rank):+ if row["file"] not in seen:+ seen.add(row["file"])+ rows.append(row)+ served = rows[:_MAX_ROWS]+ await attach_call_text(repo_root, served)+ # Unserved rows are never checked against the live file.+ for row in rows[_MAX_ROWS:]:+ row.pop("call_line", None)+ loaders = [r for r in served if r["edge_type"] in ("imports", "dynamic_imports")]+ sites = await import_sites(repo_root, [r["file"] for r in loaders], lead)+ for row in loaders:+ if site := sites.get(row["file"]):+ row["call_line"], row["text"], dynamic = site+ if dynamic:+ row["edge_type"] = "dynamic_imports"+ row.pop("wholesale", None)+ # A load found to be dynamic outranks a plain import within the served cut.+ rows[:_MAX_ROWS] = sorted(served, key=_rank)+ return rows+++def _use(row: dict) -> str:+ where = row["file"]+ if line := row.get("call_line") or row.get("line"):+ where = f"{where}:{line}"+ symbol = short_id(row["target"]) if "::" in row["target"] else "it"+ kind = row["edge_type"]+ if kind == "calls":+ via = f" via wrapper {short_id(row['via_wrapper'])}" if row.get("via_wrapper") else ""+ return f"{where} calls {symbol}{via}"+ if kind == "dynamic_imports":+ return f"{where} loads it with a dynamic import"+ if kind == "references":+ return f"{where} references {symbol}"+ return f"{where} imports {'it wholesale' if row.get('wholesale') else symbol}"+++def attach_graph_neighbors(payload: dict, rows: list[dict], lead: str | None) -> dict:+ """Add ``graph_neighbors`` (shared count fields when cut) and the keyless clause naming two users."""+ if rows and lead:+ cap_collection(payload, "graph_neighbors", rows, _MAX_ROWS)+ production = [r for r in rows if not r.get("test")][:2]+ if production:+ payload["_graph_neighbors_answer"] = (+ f"From the graph, {lead} is used by: " + "; ".join(map(_use, production)) + "."+ )+ return payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.pyindex e6e0b99ff..abeebd1bc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py@@ -295,11 +295,17 @@ def _lead_with_graph_callers(payload: dict[str, Any]) -> None:"""Open an answer no model wrote with the callers the graph found.Synthesised prose already had them as evidence; the keyless and union- replies are assembled text, so the graph's answer has to be stated.+ replies are assembled text, so the graph's answer has to be stated. The+ lead file's users follow the answer that names that file."""sentence = payload.pop("_graph_callers_answer", None)- if sentence and (payload.get("degraded") or payload.get("grounding") == "exact_symbol"):+ users = payload.pop("_graph_neighbors_answer", None)+ if not (payload.get("degraded") or payload.get("grounding") == "exact_symbol"):+ return+ if sentence:payload["answer"] = f"{sentence} {payload.get('answer') or ''}".rstrip()+ if users:+ payload["answer"] = f"{payload.get('answer') or ''} {users}".lstrip()def _keep(payload: dict[str, Any], key: str, limit: int | None) -> None:diff --git a/tests/unit/server/mcp/test_answer_graph_neighbors.py b/tests/unit/server/mcp/test_answer_graph_neighbors.pynew file mode 100644index 000000000..4af69b4bf--- /dev/null+++ b/tests/unit/server/mcp/test_answer_graph_neighbors.py@@ -0,0 +1,410 @@+"""Users of the lead file on impact questions (``tool_answer/neighbors.py``).++Synthetic graphs in TypeScript, Python and Go. A question asking which code+loads, wires or must change for something, with no caller target resolved,+gets ``graph_neighbors``; every other question is answered exactly as before.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime++import pytest++from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.server.mcp_server.tool_answer import callers, neighbors+from repowise.server.mcp_server.tool_answer.projection import project_answer_payload++_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)+++def _sym(rid, node_id, *, lines=(10, 40), kind="function", language="typescript"):+ file_path, _, qual = node_id.partition("::")+ return GraphNode(+ id=f"gn_{node_id}",+ repository_id=rid,+ node_id=node_id,+ node_type="symbol",+ name=qual.split(".")[-1],+ file_path=file_path,+ kind=kind,+ language=language,+ start_line=lines[0],+ end_line=lines[1],+ created_at=_NOW,+ )+++def _edge(rid, source, target, *, edge_type="calls", confidence=0.9, names=None, lines=None):+ return GraphEdge(+ id=f"gn_{source}->{target}:{edge_type}",+ repository_id=rid,+ source_node_id=source,+ target_node_id=target,+ edge_type=edge_type,+ confidence=confidence,+ imported_names_json=json.dumps(names) if names is not None else None,+ call_lines_json=json.dumps(lines) if lines is not None else None,+ created_at=_NOW,+ )+++def _write(root, rel: str, text: str) -> None:+ path = root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+++# ---------------------------------------------------------------------------+# Question shape+# ---------------------------------------------------------------------------+++ "question",+ [+ "Which non-test file performs that dynamic import, and which file re-exports its handler?",+ "Which bundled extension file subscribes it to the hook?",+ "If the builder changes, which non-test file actually calls it?",+ "Which module dispatches the shutdown event?",+ "If it gains a parameter, which production files must change?",+ "Who calls load_config?",+ "Which file lazily loads it at startup?",+ ],+)+def test_impact_questions_are_recognised(question):+ assert callers.is_impact_question(question, set())+++def test_uses_and_loads_need_a_code_name_or_a_pronoun():+ assert callers.is_impact_question("Which module uses parseToken?", {"parseToken"})+ assert callers.is_impact_question("Which file loads that module?", set())+++ "question",+ [+ "How does the token check validate the signature?",+ "What happens to tool calls when the stream closes?",+ "Which hashing algorithm does the app use?",+ "Where is the retry budget configured?",+ "What file uses tabs or spaces for indentation?",+ "Which function loads faster on a cold start?",+ ],+)+def test_other_questions_are_not(question):+ assert not callers.is_impact_question(question, set())+++# ---------------------------------------------------------------------------+# neighbor_evidence+# ---------------------------------------------------------------------------+++async def test_ts_lead_file_users_with_kinds(session, populated_db, tmp_path):+ """Callers, a re-exporting importer and a dynamic loader, production first."""+ rid = populated_db+ lead = "src/compaction.ts"+ session.add_all(+ [+ _sym(rid, f"{lead}::handleCompactionEnd", lines=(20, 60)),+ _sym(rid, "src/handlers.ts::createHandler", lines=(5, 50)),+ _edge(rid, "src/handlers.ts::createHandler", f"{lead}::handleCompactionEnd",+ lines=[12]),+ _edge(rid, "src/lifecycle.ts", lead, edge_type="imports", confidence=1.0,+ names=["handleCompactionEnd"]),+ _edge(rid, "src/runner.ts", lead, edge_type="imports", confidence=1.0, names=["*"]),+ _edge(rid, "src/compaction.test.ts::__module__", f"{lead}::handleCompactionEnd",+ lines=[3]),+ # Same-file plumbing is not a user.+ _edge(rid, f"{lead}::__module__", f"{lead}::handleCompactionEnd"),+ ]+ )+ await session.flush()+ _write(tmp_path, "src/handlers.ts", "\n" * 11 + " handleCompactionEnd(ctx);\n")+ _write(tmp_path, "src/lifecycle.ts",+ 'export { handleCompactionEnd } from "./compaction.js";\n')+ _write(tmp_path, "src/runner.ts",+ 'async function run() {\n const m = await import(\n "./compaction.js"\n );\n}\n')++ rows = await neighbors.neighbor_evidence(session, rid, lead, [], repo_root=tmp_path)+ assert [(r["file"], r["edge_type"]) for r in rows] == [+ ("src/handlers.ts", "calls"),+ ("src/runner.ts", "dynamic_imports"),+ ("src/lifecycle.ts", "imports"),+ ("src/compaction.test.ts", "calls"),+ ]+ assert rows[0]["call_line"] == 12 and rows[0]["text"] == "handleCompactionEnd(ctx);"+ assert rows[1]["call_line"] == 3 and "wholesale" not in rows[1]+ assert rows[2]["target"] == f"{lead}::handleCompactionEnd"+ assert rows[2]["call_line"] == 1+ assert rows[3]["test"] is True++ payload = neighbors.attach_graph_neighbors({}, rows, lead)+ assert payload["_graph_neighbors_answer"] == (+ "From the graph, src/compaction.ts is used by: src/handlers.ts:12 calls "+ "handleCompactionEnd; src/runner.ts:3 loads it with a dynamic import."+ )+++async def test_python_references_and_dynamic_import_edges(session, populated_db, tmp_path):+ rid = populated_db+ py = {"language": "python"}+ lead = "app/plugins/audit.py"+ session.add_all(+ [+ _sym(rid, f"{lead}::audit_hook", **py),+ _sym(rid, "app/registry.py::register_all", lines=(3, 20), **py),+ _edge(rid, "app/registry.py::register_all", f"{lead}::audit_hook",+ edge_type="references", confidence=0.95),+ _edge(rid, "app/loader.py", lead, edge_type="dynamic_imports", confidence=1.0),+ _edge(rid, "app/cli.py", lead, edge_type="imports", confidence=1.0,+ names=["audit_hook"]),+ ]+ )+ await session.flush()+ _write(tmp_path, "app/loader.py",+ 'import importlib\n\nmod = importlib.import_module("app.plugins.audit")\n')++ rows = await neighbors.neighbor_evidence(session, rid, lead, [], repo_root=tmp_path)+ assert [(r["file"], r["edge_type"]) for r in rows] == [+ ("app/loader.py", "dynamic_imports"),+ ("app/registry.py", "references"),+ ("app/cli.py", "imports"),+ ]+ assert rows[0]["call_line"] == 3+ # A dotted ``from`` import has no quoted path to point at.+ assert "call_line" not in rows[2]+++async def test_go_cap_and_production_first(session, populated_db):+ rid = populated_db+ go = {"language": "go"}+ lead = "store/sweep.go"+ rows = [_sym(rid, f"{lead}::RunSweep", **go)]+ for i in range(10):+ caller = f"cmd/job{i}/main.go::start"+ rows += [_sym(rid, caller, lines=(1, 20), **go), _edge(rid, caller, f"{lead}::RunSweep")]+ for i in range(3):+ caller = f"store/sweep{i}_test.go::TestSweep"+ rows += [_sym(rid, caller, lines=(1, 20), **go), _edge(rid, caller, f"{lead}::RunSweep")]+ session.add_all(rows)+ await session.flush()++ found = await neighbors.neighbor_evidence(session, rid, lead, [])+ assert len(found) == 13+ assert not any(r.get("test") for r in found[:10])+ payload = neighbors.attach_graph_neighbors({}, found, lead)+ assert len(payload["graph_neighbors"]) == 8+ assert payload["graph_neighbors_total"] == 13+ assert payload["graph_neighbors_emitted"] == 8+++async def test_question_terms_pick_which_symbol_leads(session, populated_db):+ rid = populated_db+ lead = "src/policy.ts"+ session.add_all(+ [+ _sym(rid, f"{lead}::formatReply"),+ _sym(rid, f"{lead}::createReplyToSupplier"),+ _sym(rid, "src/a.ts::send", lines=(1, 9)),+ _sym(rid, "src/b.ts::send", lines=(1, 9)),+ _sym(rid, "src/z.ts::send", lines=(1, 9)),+ _edge(rid, "src/a.ts::send", f"{lead}::formatReply"),+ _edge(rid, "src/b.ts::send", f"{lead}::formatReply"),+ _edge(rid, "src/z.ts::send", f"{lead}::createReplyToSupplier"),+ ]+ )+ await session.flush()+ hits = [{"target_path": lead, "symbols": [{"name": "createReplyToSupplier", "_relevance": 6}]}]+ rows = await neighbors.neighbor_evidence(session, rid, lead, hits)+ assert rows[0]["file"] == "src/z.ts"+++async def test_hub_keeps_the_question_symbol_users(session, populated_db, monkeypatch):+ """Edges into popular symbols past the generic cap cannot crowd out the asked-about one."""+ rid = populated_db+ monkeypatch.setattr(neighbors, "_MAX_EDGES", 5)+ lead = "src/hub.ts"+ rows = [_sym(rid, f"{lead}::popular"), _sym(rid, f"{lead}::createReplyToSupplier")]+ for i in range(10):+ rows += [_sym(rid, f"src/a{i}.ts::use", lines=(1, 9)),+ _edge(rid, f"src/a{i}.ts::use", f"{lead}::popular", confidence=0.95)]+ rows += [_sym(rid, "src/z.ts::send", lines=(1, 9)),+ _edge(rid, "src/z.ts::send", f"{lead}::createReplyToSupplier")]+ session.add_all(rows)+ await session.flush()+ hits = [{"target_path": lead, "symbols": [{"name": "createReplyToSupplier", "_relevance": 6}]}]++ found = await neighbors.neighbor_evidence(session, rid, lead, hits)+ assert found[0]["file"] == "src/z.ts"+ assert sum(r["file"].startswith("src/a") for r in found) == 5+ # Without the question's terms the capped read never reaches it.+ assert "src/z.ts" not in {r["file"] for r in await neighbors.neighbor_evidence(+ session, rid, lead, [])}+++async def test_import_line_prefers_an_import_over_a_mention(tmp_path):+ from repowise.server.mcp_server._edit_sites import import_sites++ _write(tmp_path, "src/a.ts",+ '// see "./store.js" for details\nimport { save } from "./store.js";\n')+ _write(tmp_path, "src/b.ts", 'const doc = "./store.js";\n')+ sites = await import_sites(tmp_path, ["src/a.ts", "src/b.ts"], "src/store.ts")+ assert sites["src/a.ts"][0] == 2+ # A file that only mentions the path still points at that mention.+ assert sites["src/b.ts"][0] == 1+++async def test_generic_stem_needs_its_parent_in_the_path(tmp_path):+ from repowise.server.mcp_server._edit_sites import import_sites++ _write(tmp_path, "src/a.ts",+ 'import { x } from "../other/utils.js";\nimport { y } from "../auth/utils.js";\n')+ _write(tmp_path, "src/b.ts", 'import { x } from "./utils";\n')+ _write(tmp_path, "app/c.py", 'mod = importlib.import_module("app.auth.utils")\n')+ files = ["src/a.ts", "src/b.ts", "app/c.py"]+ sites = await import_sites(tmp_path, files, "src/auth/utils.ts")+ assert sites["src/a.ts"][0] == 2+ assert "src/b.ts" not in sites+ assert sites["app/c.py"][2] is True+++async def test_test_lead_or_missing_lead_yields_nothing(session, populated_db):+ rid = populated_db+ assert await neighbors.neighbor_evidence(session, rid, None, []) == []+ assert await neighbors.neighbor_evidence(session, rid, "src/a.test.ts", []) == []+++def test_lead_file_follows_the_answer():+ assert neighbors.lead_file({"citations": ["a.ts"], "best_guesses": [{"file": "b.ts"}]}) == "a.ts"+ assert neighbors.lead_file({"citations": [], "best_guesses": [{"file": "b.ts"}]}) == "b.ts"+ assert neighbors.lead_file({"fallback_targets": ["c.ts"]}) == "c.ts"+ assert neighbors.lead_file({}) is None+++# ---------------------------------------------------------------------------+# Projection+# ---------------------------------------------------------------------------+++_ROWS = [+ {"caller": "src/b.ts::run", "file": "src/b.ts", "line": 4, "call_line": 9,+ "target": "src/a.ts::go", "edge_type": "calls"},+ {"caller": "src/c.ts", "file": "src/c.ts", "target": "src/a.ts", "edge_type": "imports",+ "wholesale": True},+]+++def test_keyless_answer_ends_with_the_lead_file_users():+ raw = {+ "answer": "x", "citations": ["src/a.ts"], "confidence": "medium",+ "retrieval_quality": "strong", "degraded": "no-llm-provider",+ "best_guesses": [{"file": "src/a.ts", "why_relevant": "defines it"}], "_meta": {},+ }+ out = project_answer_payload(neighbors.attach_graph_neighbors(raw, _ROWS, "src/a.ts"),+ question="Which file loads go?")+ assert out["answer"].endswith(+ "From the graph, src/a.ts is used by: src/b.ts:9 calls go; "+ "src/c.ts imports it wholesale."+ )+ assert out["graph_neighbors"] == _ROWS+ assert "_graph_neighbors_answer" not in out+++def test_synthesised_answer_keeps_its_prose():+ raw = {"answer": "Model prose.", "citations": ["src/a.ts"], "confidence": "high",+ "_meta": {}}+ out = project_answer_payload(neighbors.attach_graph_neighbors(raw, _ROWS, "src/a.ts"),+ question="Which file loads go?")+ assert out["answer"] == "Model prose."+ assert out["graph_neighbors"] == _ROWS+++# ---------------------------------------------------------------------------+# get_answer end to end+# ---------------------------------------------------------------------------+++async def _seed(factory, rid: str) -> None:+ async with factory() as s:+ s.add_all(+ [+ _sym(rid, "src/auth/tokens.ts::verifyToken", lines=(12, 40)),+ _sym(rid, "src/api/login.ts::handleLogin", lines=(20, 60)),+ _edge(rid, "src/api/login.ts::handleLogin", "src/auth/tokens.ts::verifyToken"),+ _edge(rid, "src/api/routes.ts", "src/auth/tokens.ts", edge_type="imports",+ confidence=1.0, names=["verifyToken"]),+ ]+ )+ await s.commit()+++def _patch_retrieval(monkeypatch, answer_mod) -> None:+ async def _fake_retrieve(question, ctx):+ return [+ {"page_id": "file_page:src/auth/tokens.ts", "score": 3.0, "_sources": {"fts"}},+ {"page_id": "file_page:src/auth/session.ts", "score": 1.0, "_sources": {"fts"}},+ ]++ async def _fake_hydrate(hits, ctx, *, scope=None):+ for h in hits:+ h["target_path"] = h["page_id"].removeprefix("file_page:")+ h.update(title=h["target_path"], summary="Token helpers.", snippet="",+ page_type="file_page")+ return hits++ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)+ monkeypatch.setenv("REPOWISE_ANSWER_DISABLE_CACHE", "1")+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: None)+++def _comparable(result: dict) -> str:+ return json.dumps({k: v for k, v in result.items() if k != "_meta"}, sort_keys=True)+++async def test_keyless_behaviour_question_lists_the_lead_file_users(+ setup_mcp, factory, monkeypatch+):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ await _seed(factory, setup_mcp)+ _patch_retrieval(monkeypatch, answer_mod)++ result = await get_answer("Which module wires in the session token helpers at startup?")+ assert "graph_callers" not in result+ assert [(r["file"], r["edge_type"]) for r in result["graph_neighbors"]] == [+ ("src/api/login.ts", "calls"),+ ("src/api/routes.ts", "imports"),+ ]+ assert "From the graph, src/auth/tokens.ts is used by: src/api/login.ts:20" in (+ result["answer"]+ )+++async def test_non_impact_answers_are_byte_identical(setup_mcp, factory, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ await _seed(factory, setup_mcp)+ _patch_retrieval(monkeypatch, answer_mod)+ question = "How are session tokens checked?"++ with_feature = await get_answer(question)+ monkeypatch.setattr(answer_mod, "is_impact_question", lambda *_a: False)+ without = await get_answer(question)+ assert "graph_neighbors" not in with_feature+ assert _comparable(with_feature) == _comparable(without)