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): answer caller and trigger questions from the call graph (#3196)
Raghav Chamadiyabc52b660cb87
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.pyindex 594bde2bb..9205ce35e 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@@ -123,6 +123,13 @@ from repowise.server.mcp_server.tool_answer.cache import (_serve_cached_answer,_write_answer_cache,)+from repowise.server.mcp_server.tool_answer.callers import (+ NO_EVIDENCE,+ attach_graph_callers,+ caller_evidence,+ caller_lines,+ is_caller_question,+)from repowise.server.mcp_server.tool_answer.confidence import (_agreement_dominant,_grade_answer,@@ -433,6 +440,18 @@ async def get_answer(homonyms = retrieved.homonymsflow_paths = retrieved.flow_paths+ # Caller questions get the graph's callers as evidence; every other+ # question skips this without a query.+ graph_callers = NO_EVIDENCE+ if is_caller_question(question, question_ids):+ try:+ async with get_session(ctx.session_factory) as session:+ graph_callers = await caller_evidence(+ session, repo_id, question, question_ids, hits, exclude_spec+ )+ except Exception:+ _log.warning("get_answer: graph caller lookup failed", exc_info=True)+# 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 = (@@ -476,7 +495,7 @@ async def get_answer(_retrieval_quality(hits, agreement_dominant),)if union_payload is not None:- return _with_candidates(union_payload, resolved_pool)+ return _with_candidates(attach_graph_callers(union_payload, graph_callers), resolved_pool)fallback_targets = [h["target_path"]@@ -519,13 +538,16 @@ async def get_answer(if not always_synthesize and not dominant:return _with_candidates(- await build_abstain_payload(- question=question,- ctx=ctx,- hits=hits,- fallback_targets=fallback_targets,- repository=repository,- t0=t0,+ 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,)@@ -568,6 +590,7 @@ async def get_answer(exclude_spec=exclude_spec,agreement_dominant=agreement_dominant,resolved_pool=resolved_pool,+ graph_callers=graph_callers,)degraded_legs = _degraded_legs(_retrieval_legs())if degraded_legs:@@ -597,6 +620,11 @@ async def get_answer(prelude = ""with contextlib.suppress(Exception):prelude = await _build_structured_prelude(hits, decisions, ctx, repo_id)+ if graph_callers.rows:+ graph_block = "Callers from the call graph:\n" + "\n".join(+ f"- {line}" for line in caller_lines(graph_callers.rows)+ )+ prelude = f"{prelude}\n\n{graph_block}" if prelude else graph_blockuser_prompt = _USER_TEMPLATE.format(question=question.strip(),@@ -663,6 +691,7 @@ async def get_answer(exclude_spec=exclude_spec,)+ attach_graph_callers(payload, graph_callers)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.pynew file mode 100644index 000000000..f424213a0--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/callers.py@@ -0,0 +1,382 @@+"""Call-graph callers as evidence for "who calls / triggers X" questions.++Retrieval answers from pages, which describe what a file does rather than who+reaches it. When the question asks for callers and names a symbol (or+retrieval's top file has a symbol matching the question), the graph's callers+of that symbol are served as ``graph_callers``, production first. Every other+question is untouched.+"""++from __future__ import annotations++import re+from pathlib import PurePosixPath+from typing import Any, NamedTuple++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._helpers import filter_dicts_by_key+from repowise.server.mcp_server._query_shape import _unmistakably_code+from repowise.server.mcp_server._wrapper_callers import (+ MIN_CALL_CONFIDENCE,+ files_importing,+ forwarding_wrapper_callers,+)+from repowise.server.mcp_server.tool_answer.config import _RELEVANCE_NAME_WEIGHT++_SUBJECT = (+ r"\b(?:who|which|what)(?:\s+(?:non-test|production|source|other|file|files|function|"+ r"functions|method|methods|code|module|modules|class|classes|component|components|"+ r"service|services|package|packages|handler|handlers|caller|callers|part|parts|place|"+ r"places|script|scripts))*\s+(?:would\s+|will\s+|can\s+|could\s+|might\s+)?"+)+#: Asks who reaches a symbol. Strong enough to resolve the symbol from retrieval+#: when the question does not name one.+_CALLER_QUESTION = re.compile(+ _SUBJECT + r"(?:calls?|invokes?|triggers?)\b"+ r"|\bwhere\s+(?:is|are|was|were)\s+[^?]{1,80}?\s+(?:called|invoked|triggered)\b"+ r"|\bcallers?\s+of\b|\bwhat\s+(?:would\s+|will\s+)?breaks?\b",+ re.IGNORECASE,+)+#: Caller verbs that also describe ordinary "where is X done" questions, so they+#: count only when the question names the symbol itself.+_NAMED_CALLER_QUESTION = re.compile(+ _SUBJECT + r"(?:uses?|registers?|references?|imports?|depends?\s+on)\b"+ r"|\bwhere\s+(?:is|are|was|were)\s+[^?]{1,80}?\s+(?:used|registered|referenced|imported)\b"+ r"|\bdepend(?:s|ing)?\s+on\b|\bused\s+by\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+_MAX_TARGETS = 4+#: Two of the question's terms in the symbol's own name.+_MIN_RETRIEVED_RELEVANCE = 2 * _RELEVANCE_NAME_WEIGHT+_MAX_RETRIEVED_TARGETS = 2+#: Callers fetched per target; the served block is cut to _MAX_ROWS after the+#: production-first sort.+_MAX_DIRECT = 50+_MAX_IMPORTER_ROWS = 3+_MAX_ROWS = 8+++class CallerEvidence(NamedTuple):+ """Graph caller rows, production first, and whether the question named the target."""++ rows: list[dict]+ named: bool = False++ @property+ def graph_answered(self) -> bool:+ """A named target with a direct production call: enough to grade on.++ Hop and importer rows are leads, and a target resolved from retrieval+ may be the wrong symbol, so neither lifts a grade.+ """+ return self.named and any(+ r["edge_type"] == "calls" and "via_wrapper" not in r and not r.get("test")+ for r in self.rows+ )+++NO_EVIDENCE = CallerEvidence([])+++def is_caller_question(question: str, question_ids: set[str]) -> bool:+ """Whether the question asks who calls, triggers or depends on something."""+ if _CALLER_QUESTION.search(question):+ return True+ return bool(_named_ids(question_ids)) and bool(_NAMED_CALLER_QUESTION.search(question))+++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)}+ leaves = {q.rsplit(".", 1)[-1] for q in ids if "." in q}+ return sorted(q for q in ids if "." in q or q not in leaves)+++def _qualifier_matches(node: GraphNode, qualifier: str) -> bool:+ """Whether ``qualifier`` (``Foo`` in ``Foo.run``) names the node's parent or module."""+ want = qualifier.rsplit(".", 1)[-1].lower()+ local = node.node_id.split("::", 1)[-1]+ parents = {+ *(part.lower() for part in (node.qualified_name or "").split(".")[:-1]),+ *(part.lower() for part in local.split(".")[:-1]),+ }+ return want in parents or PurePosixPath(node.file_path or "").stem.lower() == want+++async def _named_targets(+ session: AsyncSession, repo_id: str, names: list[str]+) -> list[GraphNode]:+ res = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "symbol",+ GraphNode.name.in_({n.rsplit(".", 1)[-1] for n in names}),+ GraphNode.kind.in_(_TARGET_KINDS),+ )+ )+ by_leaf: dict[str, list[GraphNode]] = {}+ for node in res.scalars().all():+ if node.file_path and not is_test_path(node.file_path, node.language):+ by_leaf.setdefault(node.name, []).append(node)+ out: list[GraphNode] = []+ for name in names:+ qualifier, _, leaf = name.rpartition(".")+ defs = by_leaf.get(leaf, [])+ # A qualifier that matches no definition drops the name rather than+ # widening it to every same-named symbol.+ if qualifier:+ defs = [n for n in defs if _qualifier_matches(n, qualifier)]+ if 0 < len(defs) <= _MAX_DEFS_PER_NAME:+ out.extend(n for n in sorted(defs, key=lambda n: n.node_id) if n not in out)+ return out[:_MAX_TARGETS]+++async def _retrieved_targets(+ session: AsyncSession, repo_id: str, hits: list[dict]+) -> list[GraphNode]:+ """The top hit's symbols whose names carry the question's terms."""+ top = hits[0] if hits else {}+ path = top.get("target_path")+ if not path or is_test_path(path):+ return []+ picked = sorted(+ (+ s+ for s in top.get("symbols") or []+ if s.get("kind") in _TARGET_KINDS+ and (s.get("_relevance") or 0) >= _MIN_RETRIEVED_RELEVANCE+ ),+ key=lambda s: (-(s.get("_relevance") or 0), s.get("start_line") or 0),+ )[:_MAX_RETRIEVED_TARGETS]+ if not picked:+ return []+ res = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "symbol",+ GraphNode.file_path == path,+ GraphNode.name.in_([s["name"] for s in picked]),+ )+ )+ order = {s["name"]: i for i, s in enumerate(picked)}+ return sorted(res.scalars().all(), key=lambda n: (order.get(n.name, 99), n.node_id))+++def _row(caller: str, file: str, line: int | None, target: str, edge_type: str) -> dict:+ row: dict[str, Any] = {"caller": caller, "file": file}+ # A module-level caller sits at line 0, which names no line to open.+ if line:+ row["line"] = line+ row["target"] = target+ row["edge_type"] = edge_type+ return row+++async def _direct_edges(+ session: AsyncSession, repo_id: str, target: GraphNode, *, cross_file: bool+) -> list[GraphEdge]:+ """One target's inbound calls, capped on their own so a hub cannot starve the rest."""+ res = await session.execute(+ select(GraphEdge)+ .where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id == target.node_id,+ GraphEdge.edge_type == "calls",+ GraphEdge.confidence >= MIN_CALL_CONFIDENCE,+ )+ .order_by(GraphEdge.confidence.desc(), GraphEdge.source_node_id)+ .limit(_MAX_DIRECT)+ )+ return [+ e+ for e in res.scalars().all()+ if e.source_node_id != target.node_id+ and not (cross_file and e.source_node_id.split("::")[0] == target.file_path)+ ]+++async def caller_evidence(+ session: AsyncSession,+ repo_id: str,+ question: str,+ question_ids: set[str],+ hits: list[dict],+ exclude_spec: Any = None,+) -> CallerEvidence:+ """Graph callers of the symbol a caller question asks about, production first.++ Named targets list every caller; a target resolved from retrieval lists only+ callers in other files, since its own file's plumbing is not what triggers+ it. A forwarding wrapper's callers come one hop further (``via_wrapper``),+ and a production caller nothing in production calls is followed to the+ files importing it by name, which is how a handler or extension gets+ registered.+ """+ if not is_caller_question(question, question_ids):+ return NO_EVIDENCE+ named = _named_ids(question_ids)+ targets = await _named_targets(session, repo_id, named) if named else []+ cross_file = not targets+ if cross_file:+ if not _CALLER_QUESTION.search(question):+ return NO_EVIDENCE+ targets = await _retrieved_targets(session, repo_id, hits)+ if not targets:+ return NO_EVIDENCE++ edges = {+ t.node_id: await _direct_edges(session, repo_id, t, cross_file=cross_file)+ for t in targets+ }+ nodes = await get_graph_nodes_by_ids(+ session, repo_id, list({e.source_node_id for es in edges.values() for e in es})+ )++ rows: list[dict] = []+ seen: set[str] = set()+ for target in targets:+ mine = edges[target.node_id]+ for e in mine:+ if e.source_node_id in seen:+ continue+ seen.add(e.source_node_id)+ src = nodes.get(e.source_node_id)+ rows.append(+ _row(+ e.source_node_id,+ src.file_path if src else e.source_node_id.split("::")[0],+ src.start_line if src else None,+ target.node_id,+ "calls",+ )+ )+ hop = await forwarding_wrapper_callers(+ session, repo_id, target, [e.source_node_id for e in mine], known_nodes=nodes+ )+ for h in hop:+ caller = h.get("symbol_id") or h["file"]+ if caller in seen or (cross_file and h["file"] == target.file_path):+ continue+ seen.add(caller)+ row = _row(+ caller, h["file"], h.get("line"), target.node_id, h.get("edge_type") or "imports"+ )+ if h.get("wholesale"):+ row["wholesale"] = True+ row["via_wrapper"] = h["via_wrapper"]+ rows.append(row)++ rows.extend(await _registering_files(session, repo_id, rows, nodes))+ for row in rows:+ if is_test_path(row["file"]):+ row["test"] = True+ rows = filter_dicts_by_key(rows, "file", exclude_spec)+ rows.sort(key=lambda r: bool(r.get("test")))+ return CallerEvidence(rows, named=not cross_file)+++async def _registering_files(+ session: AsyncSession, repo_id: str, rows: list[dict], nodes: dict[str, GraphNode]+) -> list[dict]:+ """Files importing, by name, a production caller that no production code calls."""+ callers = [+ nodes[r["caller"]]+ for r in rows+ if r["edge_type"] == "calls"+ and "via_wrapper" not in r+ and r["caller"] in nodes+ and nodes[r["caller"]].kind in ("function", "method", "class")+ and not is_test_path(r["file"])+ ]+ if not callers:+ return []+ res = await session.execute(+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.target_node_id.in_([c.node_id for c in callers]),+ GraphEdge.edge_type == "calls",+ GraphEdge.confidence >= MIN_CALL_CONFIDENCE,+ )+ )+ called = {dst for src, dst in res.all() if not is_test_path(src.split("::")[0])}+ unreached = [c for c in callers if c.node_id not in called]+ if not unreached:+ return []+ listed = {r["file"] for r in rows} | {c.file_path for c in unreached}+ # A wholesale import (a barrel, ``import *``) does not say this symbol is used.+ imported = [t for t in await files_importing(session, repo_id, unreached, listed) if t[3]]+ # Production importers first, so a test importing the same symbol cannot+ # take the only slots.+ imported.sort(key=lambda t: is_test_path(t[0]))+ return [+ _row(importer, importer, None, symbol_id, "imports")+ for importer, _conf, symbol_id, _named in imported[:_MAX_IMPORTER_ROWS]+ ]+++def attach_graph_callers(payload: dict, evidence: CallerEvidence) -> dict:+ """Add ``graph_callers`` (shared count fields when cut) and the keyless answer lead.++ The lead is written from every row, not the served cut, so its counts are+ true; the projection states it only where no model wrote the answer.+ """+ if evidence.rows:+ cap_collection(payload, "graph_callers", evidence.rows, _MAX_ROWS)+ if sentence := caller_sentence(evidence.rows):+ payload["_graph_callers_answer"] = sentence+ return payload+++def _short(symbol_id: str) -> str:+ return symbol_id.split("::")[-1] if "::" in symbol_id else symbol_id+++def _phrase(row: dict) -> str:+ where = f"{row['file']}:{row['line']}" if row.get("line") is not None else row["file"]+ target = _short(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 "")):+ 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}"+ )+ if wrapper:+ return (+ f"{row['file']} imports wrapper {_short(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}"+++def caller_lines(rows: list[dict]) -> list[str]:+ """One plain sentence per caller row, production rows first as served."""+ return [_phrase(r) + (" [test]" if r.get("test") else "") for r in rows[:_MAX_ROWS]]+++def caller_sentence(rows: list[dict]) -> str | None:+ """The keyless ``answer`` lead: production rows, then the count of test callers."""+ production = [r for r in rows if not r.get("test")]+ tests = sum(1 for r in rows if r.get("test") and r["edge_type"] == "calls")+ parts = [_phrase(r) for r in production[:_MAX_ROWS]]+ if tests:+ parts.append(f"{tests} test caller{'s' if tests != 1 else ''}")+ if not parts:+ return None+ return "From the call graph: " + "; ".join(parts) + "."diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py b/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.pyindex a0cc3fa72..57c9139c5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/confidence.py@@ -528,7 +528,11 @@ def lead_leaves_retrieval(hits: list[dict], lead: str | None) -> bool:def _degraded_confidence(- reason: str, retrieval_quality: str, *, lead_outside_top: bool = False+ reason: str,+ retrieval_quality: str,+ *,+ lead_outside_top: bool = False,+ graph_answered: bool = False,) -> str:"""Grade a synthesis-less payload on what a caller can act on, not on prose.@@ -546,7 +550,12 @@ def _degraded_confidence(A strong retrieval still grades "low" when the answer leads with a file itdoes not back (:func:`lead_leaves_retrieval`): "medium" tells the caller tostart from that lead.++ ``graph_answered`` (a caller question the call graph answered) grades+ "medium" on its own: the answer then leads with graph edges, not retrieval."""+ if reason == "no-llm-provider" and graph_answered:+ return "medium"if reason != "no-llm-provider" or lead_outside_top:return "low"return "low" if retrieval_quality == "weak" else "medium"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 f3a481bf8..7266a356c 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@@ -279,7 +279,8 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5# round of provider spend.# 18: rows carry ``candidate_files``, the ranked paths-only list.# 19: rows carry ``_candidate_file_facts``; low answers serve slim best_guesses rows.-_ANSWER_SCHEMA_VERSION = 19+# 20: caller questions carry ``graph_callers`` and synthesise with them.+_ANSWER_SCHEMA_VERSION = 20# 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/degraded.py b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.pyindex 95d89c17e..2f45317e3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py@@ -16,6 +16,11 @@ from repowise.server.mcp_server.tool_answer.bodies import (_build_symbol_bodies,_gather_body_candidates,)+from repowise.server.mcp_server.tool_answer.callers import (+ NO_EVIDENCE,+ CallerEvidence,+ attach_graph_callers,+)from repowise.server.mcp_server.tool_answer.confidence import (_degraded_confidence,_retrieval_quality,@@ -105,6 +110,7 @@ async def _degraded_payload(exclude_spec=None,agreement_dominant: bool = False,resolved_pool: list[dict] | None = None,+ graph_callers: CallerEvidence = NO_EVIDENCE,) -> dict:"""Shape a synthesis-less get_answer response.@@ -153,7 +159,10 @@ async def _degraded_payload(else:lead = code_rationale[0].get("path") if code_rationale else Noneconfidence = _degraded_confidence(- reason, retrieval_quality, lead_outside_top=lead_leaves_retrieval(hits, lead)+ reason,+ retrieval_quality,+ lead_outside_top=lead_leaves_retrieval(hits, lead),+ graph_answered=graph_callers.graph_answered,)payload: dict = {@@ -168,6 +177,7 @@ async def _degraded_payload(}if best_guesses:payload["best_guesses"] = best_guesses+ attach_graph_callers(payload, graph_callers)if code_rationale:payload["code_rationale"] = code_rationalepayload["note"] += (diff --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 1945435a7..88fabfe76 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@@ -291,6 +291,17 @@ def _rewrite_degraded_answer(payload: dict[str, Any]) -> None:)+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.+ """+ sentence = payload.pop("_graph_callers_answer", None)+ if sentence and (payload.get("degraded") or payload.get("grounding") == "exact_symbol"):+ payload["answer"] = f"{sentence} {payload.get('answer') or ''}".rstrip()++def _keep(payload: dict[str, Any], key: str, limit: int | None) -> None:rows = payload.get(key)if not isinstance(rows, list):@@ -673,6 +684,7 @@ def _project(ranked = not expanded and _ranked_list_only(payload)if ranked:_serve_ranked_list(payload)+ _lead_with_graph_callers(payload)for key in _COLLECTIONS:if not payload.get(key):payload.pop(key, None)diff --git a/tests/unit/server/mcp/test_answer_graph_callers.py b/tests/unit/server/mcp/test_answer_graph_callers.pynew file mode 100644index 000000000..b34b97a7f--- /dev/null+++ b/tests/unit/server/mcp/test_answer_graph_callers.py@@ -0,0 +1,466 @@+"""Caller questions answered from the call graph (``tool_answer/callers.py``).++Synthetic graphs in TypeScript, Python and Go. A question asking who calls,+triggers or registers a symbol gets ``graph_callers``; every other question is+answered exactly as before.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from types import SimpleNamespace++import pytest++from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.server.mcp_server.tool_answer import callers+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"gc_{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):+ return GraphEdge(+ id=f"gc_{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,+ created_at=_NOW,+ )+++# ---------------------------------------------------------------------------+# Question shape+# ---------------------------------------------------------------------------+++ "question, ids",+ [+ ("Which non-test files call parseToken?", {"parseToken"}),+ ("Who calls load_config?", {"load_config"}),+ ("What would break if OpenStore changes its signature?", {"OpenStore"}),+ ("Where is load_config called from?", {"load_config"}),+ ("Which file triggers the nightly sweep?", set()),+ ("Which module registers renderWidget as a plugin?", {"renderWidget"}),+ ("Which handlers depend on load_config?", {"load_config"}),+ ],+)+def test_caller_questions_are_recognised(question, ids):+ assert callers.is_caller_question(question, ids)+++ "question, ids",+ [+ ("How does parseToken validate the signature?", {"parseToken"}),+ ("What happens to tool calls when the stream closes?", set()),+ ("Which hashing algorithm does the app use?", set()),+ # A registration verb without a code-shaped name is a "where" question.+ ("Which file registers the global hotkey?", set()),+ ("Which file registers the global hotkey? List them.", {"List"}),+ ],+)+def test_other_questions_are_not(question, ids):+ assert not callers.is_caller_question(question, ids)+++# ---------------------------------------------------------------------------+# caller_evidence+# ---------------------------------------------------------------------------+++async def test_ts_wrapper_and_registration_rows(session, populated_db):+ """Production callers lead, a wrapper's importer is marked, a registering file is found."""+ rid = populated_db+ session.add_all(+ [+ _sym(rid, "src/quality.ts::auditSummary", lines=(200, 230)),+ _sym(rid, "src/quality.runtime.ts::auditSummary", lines=(5, 9)),+ _sym(rid, "src/safeguard.ts::safeguardExtension", lines=(800, 900)),+ _sym(rid, "src/quality.test.ts::__module__", lines=(0, 300), kind="module"),+ _edge(rid, "src/quality.test.ts::__module__", "src/quality.ts::auditSummary"),+ _edge(rid, "src/safeguard.ts::safeguardExtension", "src/quality.ts::auditSummary"),+ _edge(rid, "src/quality.runtime.ts::auditSummary", "src/quality.ts::auditSummary"),+ _edge(rid, "src/diag.ts", "src/quality.runtime.ts", edge_type="imports",+ confidence=1.0, names=["*"]),+ _edge(rid, "src/runner/extensions.ts", "src/safeguard.ts", edge_type="imports",+ confidence=1.0, names=["safeguardExtension"]),+ _edge(rid, "src/runner/extensions.test.ts", "src/safeguard.ts", edge_type="imports",+ confidence=1.0, names=["safeguardExtension"]),+ # A barrel re-exporting everything names no symbol: never a registration.+ _edge(rid, "src/index.ts", "src/safeguard.ts", edge_type="imports",+ confidence=1.0, names=["*"]),+ ]+ )+ await session.flush()++ ev = await callers.caller_evidence(+ session, rid, "Which file calls auditSummary, and which file registers that caller?",+ {"auditSummary"}, [],+ )+ rows = ev.rows+ files = [r["file"] for r in rows]+ # Both definitions are targets; the runtime wrapper is itself a caller.+ assert "src/safeguard.ts" in files+ assert "src/quality.runtime.ts" in files+ assert "src/index.ts" not in files+ diag = next(r for r in rows if r["file"] == "src/diag.ts")+ assert diag["via_wrapper"] == "src/quality.runtime.ts::auditSummary"+ assert diag["edge_type"] == "imports" and diag["wholesale"] is True+ reg = next(r for r in rows if r["file"] == "src/runner/extensions.ts")+ assert reg == {+ "caller": "src/runner/extensions.ts",+ "file": "src/runner/extensions.ts",+ "target": "src/safeguard.ts::safeguardExtension",+ "edge_type": "imports",+ }+ tests = [i for i, r in enumerate(rows) if r.get("test")]+ assert tests and min(tests) > max(i for i, r in enumerate(rows) if not r.get("test"))+ module_row = next(r for r in rows if r["file"] == "src/quality.test.ts")+ assert "line" not in module_row++ sentence = callers.caller_sentence(rows)+ assert sentence.startswith("From the call graph: ")+ assert "safeguardExtension (src/safeguard.ts:800) calls auditSummary;" in sentence+ # Same-named wrapper and target: the target's file tells them apart.+ assert (+ "auditSummary (src/quality.runtime.ts:5) calls auditSummary in src/quality.ts" in sentence+ )+ assert "src/diag.ts loads src/quality.runtime.ts wholesale" in sentence+ assert "src/runner/extensions.ts imports safeguardExtension" in sentence+ # The test importer is not a caller; only the test module that calls is counted.+ assert sentence.endswith("; 1 test caller.")+++async def test_python_named_target_lists_every_caller(session, populated_db):+ rid = populated_db+ py = {"language": "python"}+ session.add_all(+ [+ _sym(rid, "app/config.py::load_config", **py),+ _sym(rid, "app/config.py::reload", lines=(50, 70), **py),+ _sym(rid, "app/cli.py::main", lines=(1, 30), **py),+ _edge(rid, "app/config.py::reload", "app/config.py::load_config"),+ _edge(rid, "app/cli.py::main", "app/config.py::load_config", confidence=0.95),+ _edge(rid, "app/noise.py::guess", "app/config.py::load_config", confidence=0.5),+ ]+ )+ await session.flush()++ ev = await callers.caller_evidence(+ session, rid, "Who calls load_config?", {"load_config"}, []+ )+ # Same-file callers count for a named target; the 0.5 edge does not.+ assert [r["caller"] for r in ev.rows] == ["app/cli.py::main", "app/config.py::reload"]+ assert ev.rows[0]["line"] == 1+ assert ev.named and ev.graph_answered+++async def test_qualified_name_keeps_its_qualifier(session, populated_db):+ """``Store.save`` picks the method under ``Store``; an unmatched qualifier drops the name."""+ rid = populated_db+ py = {"language": "python"}+ session.add_all(+ [+ _sym(rid, "app/store.py::Store.save", kind="method", **py),+ _sym(rid, "app/cache.py::Cache.save", kind="method", **py),+ _sym(rid, "app/api.py::put", lines=(1, 20), **py),+ _sym(rid, "app/jobs.py::flush", lines=(1, 20), **py),+ _edge(rid, "app/api.py::put", "app/store.py::Store.save"),+ _edge(rid, "app/jobs.py::flush", "app/cache.py::Cache.save"),+ ]+ )+ await session.flush()++ ev = await callers.caller_evidence(+ session, rid, "Who calls Store.save?", {"Store.save", "Store", "save"}, []+ )+ assert [r["caller"] for r in ev.rows] == ["app/api.py::put"]+ # A module qualifier matches the file stem.+ ev = await callers.caller_evidence(+ session, rid, "Who calls cache.save?", {"cache.save", "save"}, []+ )+ assert [r["caller"] for r in ev.rows] == ["app/jobs.py::flush"]+ missed = await callers.caller_evidence(+ session, rid, "Who calls Ledger.save?", {"Ledger.save", "Ledger", "save"}, []+ )+ assert missed.rows == []+++async def test_go_target_resolved_from_retrieval_lists_other_files_only(session, populated_db):+ rid = populated_db+ go = {"language": "go"}+ session.add_all(+ [+ _sym(rid, "store/sweep.go::RunNightlySweep", **go),+ _sym(rid, "store/sweep.go::scheduleSweep", lines=(60, 90), **go),+ _sym(rid, "cmd/server/main.go::startJobs", lines=(5, 40), **go),+ _edge(rid, "store/sweep.go::scheduleSweep", "store/sweep.go::RunNightlySweep"),+ _edge(rid, "cmd/server/main.go::startJobs", "store/sweep.go::RunNightlySweep"),+ ]+ )+ await session.flush()+ hits = [+ {+ "target_path": "store/sweep.go",+ "symbols": [+ {"name": "RunNightlySweep", "kind": "function", "_relevance": 6, "start_line": 10},+ {"name": "scheduleSweep", "kind": "function", "_relevance": 3, "start_line": 60},+ ],+ }+ ]++ ev = await callers.caller_evidence(+ session, rid, "Which file triggers the nightly sweep?", set(), hits+ )+ assert [r["caller"] for r in ev.rows] == ["cmd/server/main.go::startJobs"]+ # A target retrieval guessed does not lift a grade.+ assert not ev.named and not ev.graph_answered+++async def test_hub_target_does_not_starve_the_others(session, populated_db, monkeypatch):+ rid = populated_db+ monkeypatch.setattr(callers, "_MAX_DIRECT", 3)+ rows = [+ _sym(rid, "lib/a.ts::hubCall"),+ _sym(rid, "lib/b.ts::hubCall"),+ _sym(rid, "app/only.ts::useB", lines=(1, 20)),+ _edge(rid, "app/only.ts::useB", "lib/b.ts::hubCall", confidence=0.8),+ ]+ for i in range(6):+ rows.append(_sym(rid, f"app/u{i}.ts::useA", lines=(1, 20)))+ rows.append(_edge(rid, f"app/u{i}.ts::useA", "lib/a.ts::hubCall", confidence=0.95))+ session.add_all(rows)+ await session.flush()++ ev = await callers.caller_evidence(session, rid, "Who calls hubCall?", {"hubCall"}, [])+ found = [r["caller"] for r in ev.rows]+ assert "app/only.ts::useB" in found+ assert sum(c.endswith("::useA") for c in found) == 3+++def test_only_a_direct_production_call_lifts_the_grade():+ hop = {"caller": "src/app.ts", "file": "src/app.ts", "target": "src/core.ts::run",+ "edge_type": "imports", "via_wrapper": "src/core.runtime.ts::run"}+ via = {"caller": "src/app.ts::main", "file": "src/app.ts", "line": 3,+ "target": "src/core.ts::run", "edge_type": "calls",+ "via_wrapper": "src/core.runtime.ts::run"}+ reg = {"caller": "src/ext.ts", "file": "src/ext.ts", "target": "src/core.ts::run",+ "edge_type": "imports"}+ test_call = {"caller": "src/core.test.ts::__module__", "file": "src/core.test.ts",+ "target": "src/core.ts::run", "edge_type": "calls", "test": True}+ direct = {"caller": "src/cli.ts::main", "file": "src/cli.ts", "line": 1,+ "target": "src/core.ts::run", "edge_type": "calls"}+ assert not callers.CallerEvidence([hop, via, reg, test_call], named=True).graph_answered+ assert callers.CallerEvidence([direct], named=True).graph_answered+ assert not callers.CallerEvidence([direct], named=False).graph_answered+++async def test_unresolvable_target_yields_nothing(session, populated_db):+ rid = populated_db+ ev = await callers.caller_evidence(+ session, rid, "Which file calls missingThing?", {"missingThing"}, []+ )+ assert ev.rows == []+ # A weak verb without a resolvable named target does not fall back to retrieval.+ ev = await callers.caller_evidence(+ session, rid, "Which module uses missingThing?", {"missingThing"},+ [{"target_path": "a.py", "symbols": [{"name": "x", "kind": "function", "_relevance": 9}]}],+ )+ assert ev.rows == []+++# ---------------------------------------------------------------------------+# Projection+# ---------------------------------------------------------------------------+++def _degraded_raw(**extra) -> dict:+ return {+ "answer": "No synthesized prose (no-llm-provider).",+ "citations": ["src/a.ts"],+ "confidence": "medium",+ "retrieval_quality": "strong",+ "degraded": "no-llm-provider",+ "retrieval": [{"target_path": "src/a.ts", "score": 3.0}],+ "best_guesses": [{"file": "src/a.ts", "why_relevant": "defines it"}],+ "note": "n",+ "_meta": {},+ **extra,+ }+++def test_keyless_answer_leads_with_the_graph_callers():+ rows = [+ {"caller": "src/b.ts::run", "file": "src/b.ts", "line": 4, "target": "src/a.ts::go",+ "edge_type": "calls"},+ ]+ raw = callers.attach_graph_callers(_degraded_raw(), callers.CallerEvidence(rows, named=True))+ out = project_answer_payload(raw, question="Who calls go?")+ assert out["answer"].startswith("From the call graph: run (src/b.ts:4) calls go.")+ assert out["graph_callers"] == rows+ assert "_graph_callers_answer" not in out+++def test_test_caller_count_comes_from_every_row_not_the_served_cut():+ rows = [+ {"caller": "src/b.ts::run", "file": "src/b.ts", "line": 4, "target": "src/a.ts::go",+ "edge_type": "calls"},+ ] + [+ {"caller": f"t/t{i}.ts::case", "file": f"t/t{i}.test.ts", "line": 1,+ "target": "src/a.ts::go", "edge_type": "calls", "test": True}+ for i in range(12)+ ]+ raw = callers.attach_graph_callers(_degraded_raw(), callers.CallerEvidence(rows, named=True))+ out = project_answer_payload(raw, question="Who calls go?")+ assert len(out["graph_callers"]) == 8+ assert out["graph_callers_total"] == 13+ assert "12 test callers." in out["answer"]+++def test_projection_unchanged_without_graph_callers():+ raw = _degraded_raw()+ assert "From the call graph" not in project_answer_payload(raw, question="x")["answer"]+++# ---------------------------------------------------------------------------+# get_answer end to end+# ---------------------------------------------------------------------------+++async def _seed_auth_graph(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)),+ _sym(rid, "src/auth/tokens.test.ts::__module__", lines=(0, 90), kind="module"),+ _edge(rid, "src/api/login.ts::handleLogin", "src/auth/tokens.ts::verifyToken"),+ _edge(rid, "src/auth/tokens.test.ts::__module__", "src/auth/tokens.ts::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")+++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_caller_question_names_the_callers(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_auth_graph(factory, setup_mcp)+ _patch_retrieval(monkeypatch, answer_mod)+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: None)++ result = await get_answer("Which non-test files call verifyToken?")+ assert result["answer"].startswith(+ "From the call graph: handleLogin (src/api/login.ts:20) calls verifyToken; "+ "1 test caller."+ )+ assert [r["file"] for r in result["graph_callers"]] == [+ "src/api/login.ts",+ "src/auth/tokens.test.ts",+ ]+ assert result["confidence"] == "medium"+++async def test_keyed_caller_question_hands_the_callers_to_synthesis(+ 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_auth_graph(factory, setup_mcp)+ _patch_retrieval(monkeypatch, answer_mod)+ prompts: list[str] = []++ class _Provider:+ provider_name = "mock"+ model_name = "mock-1"++ async def generate(self, **kwargs):+ prompts.append(json.dumps(kwargs, default=str))+ return SimpleNamespace(content="handleLogin calls it (src/api/login.ts).")++ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: _Provider())++ result = await get_answer("Which non-test files call verifyToken?")+ assert prompts and "Callers from the call graph:" in prompts[0]+ assert "handleLogin (src/api/login.ts:20) calls verifyToken" in prompts[0]+ assert result["answer"] == "handleLogin calls it (src/api/login.ts)."+ assert result["graph_callers"][0]["file"] == "src/api/login.ts"+++ "question",+ [+ "How does verifyToken check the signature?",+ # A caller question whose named target the graph does not hold.+ "Which files call refreshSessionCookie?",+ ],+)+async def test_other_answers_are_byte_identical(setup_mcp, factory, monkeypatch, question):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ await _seed_auth_graph(factory, setup_mcp)+ _patch_retrieval(monkeypatch, answer_mod)+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: None)++ with_feature = await get_answer(question)+ monkeypatch.setattr(answer_mod, "is_caller_question", lambda *_a: False)+ without = await get_answer(question)+ assert "graph_callers" not in with_feature+ assert _comparable(with_feature) == _comparable(without)