Skip to content

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

feat(context): show the calling line on caller rows (#3198)

Raghav Chamadiyaee341b77e7de
diff --git a/packages/server/src/repowise/server/mcp_server/_edit_sites.py b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
index 253fb7ef9..27b838b4a 100644
--- a/packages/server/src/repowise/server/mcp_server/_edit_sites.py
+++ b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
@@ -103,6 +103,107 @@ def _read_lines(root: Path, rel: str) -> list[str] | None:
return [line.removesuffix("\r") for line in text.removesuffix("\n").split("\n")]
+def first_call_line(lines_json: str | None) -> int | None:
+ """The earliest line in an edge's ``call_lines_json``, or None when it records none."""
+ try:
+ lines = [int(n) for n in json.loads(lines_json or "[]")]
+ except (TypeError, ValueError):
+ return None
+ return min((n for n in lines if n > 0), default=None)
+
+
+def _word(name: str) -> re.Pattern[str]:
+ """*name* as a whole identifier."""
+ return re.compile(rf"(?<![\w$]){re.escape(name)}(?![\w$])")
+
+
+def _renames(
+ lines: list[str], name: str, imports: set[int], python: bool
+) -> tuple[set[str], set[str]]:
+ """``(every name *name* is renamed to, those bound by an import)`` in this file."""
+ esc = re.escape(name)
+ word = _word(name)
+ as_rename = re.compile(rf"(?<![\w$.]){esc}\s+as\s+([\w$]+)")
+ # ``{ name: other } = require(...)`` or a destructured import; a ternary's
+ # ``name : other`` is excluded, anything else colon-shaped counts.
+ colon_rename = re.compile(rf"(?<![\w$.?]){esc}\s*:\s*([A-Za-z_$][\w$]*)")
+ ternary = re.compile(rf"\?[^:]*(?<![\w$]){esc}\s*:")
+ aliases: set[str] = set()
+ # Aliases bound by an import; a rename anywhere else is always a hole.
+ imported: set[str] = set()
+ for n, text in enumerate(lines, 1):
+ if not word.search(text):
+ continue
+ found = [m.group(1) for m in as_rename.finditer(text)] if n in imports else []
+ if not python and not ternary.search(text):
+ found += [m.group(1) for m in colon_rename.finditer(text)]
+ aliases.update(found)
+ if n in imports:
+ imported.update(found)
+ # ``name as default`` is a default export, not a rename.
+ aliases.discard("default")
+ return aliases, aliases & imported
+
+
+def _call_texts(
+ root: Path, wanted: dict[str, set[tuple[int, str]]]
+) -> dict[tuple[str, int, str], str]:
+ """``(file, line, name) -> text`` for each line that still names *name* or its import alias."""
+ out: dict[tuple[str, int, str], str] = {}
+ for rel, asks in wanted.items():
+ lines = _read_lines(root, rel)
+ if lines is None:
+ continue
+ imports: set[int] | None = None
+ for n, name in asks:
+ if not 0 < n <= len(lines):
+ continue
+ text = lines[n - 1]
+ if not _word(name).search(text):
+ if imports is None:
+ imports = _import_lines(lines)
+ python = Path(rel).suffix in _PYTHON_EXTENSIONS
+ _, local = _renames(lines, name, imports, python)
+ if not any(_word(a).search(text) for a in local):
+ continue
+ out[(rel, n, name)] = text.strip()[:MAX_TEXT_CHARS]
+ return out
+
+
+def _leaf(symbol_id: str) -> str:
+ return id_segment_name(symbol_id.split("::")[-1].split(".")[-1])
+
+
+async def attach_call_text(
+ repo_root: str | Path | None, rows: list[dict[str, Any]], callee_id: str | None = None
+) -> None:
+ """Add ``text``, the live source at ``call_line``, where that line still names the callee.
+
+ The callee is the row's ``via_wrapper``, else its ``target``, else
+ *callee_id*. A line that no longer names it (the file moved under the
+ index), or a file that cannot be read, loses ``call_line`` too, so no
+ stale line is served. One read per distinct file, off the event loop.
+ """
+ asks: dict[int, tuple[str, int, str]] = {}
+ for i, row in enumerate(rows):
+ callee = row.get("via_wrapper") or row.get("target") or callee_id
+ if row.get("call_line") and row.get("file") and callee:
+ asks[i] = (row["file"], row["call_line"], _leaf(callee))
+ if not asks:
+ return
+ texts: dict[tuple[str, int, str], str] = {}
+ if repo_root:
+ wanted: dict[str, set[tuple[int, str]]] = {}
+ for rel, n, name in asks.values():
+ wanted.setdefault(rel, set()).add((n, name))
+ texts = await asyncio.to_thread(_call_texts, Path(repo_root).resolve(), wanted)
+ for i, key in asks.items():
+ if text := texts.get(key):
+ rows[i]["text"] = text
+ else:
+ rows[i].pop("call_line", None)
+
+
def _scan(
root: Path,
files: list[str],
@@ -112,13 +213,7 @@ def _scan(
) -> tuple[list[dict[str, Any]], list[str], int, set[str], bool, dict[str, set[str]]]:
"""``(sites, unreadable, stale call lines, files renaming it, default-exported,
local import aliases per Python file)``."""
- esc = re.escape(name)
- word = re.compile(rf"(?<![\w$]){esc}(?![\w$])")
- as_rename = re.compile(rf"(?<![\w$.]){esc}\s+as\s+([\w$]+)")
- # ``{ name: other } = require(...)`` or a destructured import; a ternary's
- # ``name : other`` is excluded, anything else colon-shaped counts.
- colon_rename = re.compile(rf"(?<![\w$.?]){esc}\s*:\s*([A-Za-z_$][\w$]*)")
- ternary = re.compile(rf"\?[^:]*(?<![\w$]){esc}\s*:")
+ word = _word(name)
# Bound under any name by its importers, so no spelling can be scanned for.
default_export = re.compile(r"\bexport\s+default\b|\bas\s+default\b")
def_path, def_start, def_end = definition
@@ -135,22 +230,8 @@ def _scan(
continue
imports = _import_lines(lines)
python = Path(rel).suffix in _PYTHON_EXTENSIONS
- aliases: set[str] = set()
- # Aliases bound by an import; a rename anywhere else is always a hole.
- imported: set[str] = set()
- for n, text in enumerate(lines, 1):
- if not word.search(text):
- continue
- found = [m.group(1) for m in as_rename.finditer(text)] if n in imports else []
- if not python and not ternary.search(text):
- found += [m.group(1) for m in colon_rename.finditer(text)]
- aliases.update(found)
- if n in imports:
- imported.update(found)
- # ``name as default`` is the default-export case below, not a rename.
- aliases.discard("default")
- local = aliases & imported
- if aliases - imported or _aliases_leave(rel, lines, local, imports):
+ aliases, local = _renames(lines, name, imports, python)
+ if aliases - local or _aliases_leave(rel, lines, local, imports):
renamed.add(rel)
elif python and local:
python_aliases[rel] = local
@@ -159,7 +240,7 @@ def _scan(
commonjs = any(_CJS_EXPORT.search(t) for t in lines)
if commonjs or any(default_export.search(t) and word.search(t) for t in lines):
is_default = True
- spellings = [word] + [re.compile(rf"(?<![\w$]){re.escape(a)}(?![\w$])") for a in aliases]
+ spellings = [word] + [_word(a) for a in aliases]
graph_calls = call_lines.get(rel, set())
def_seen = rel != def_path
for n, text in enumerate(lines, 1):
diff --git a/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py
index ee214a4a5..7f57698c1 100644
--- a/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py
+++ b/packages/server/src/repowise/server/mcp_server/_wrapper_callers.py
@@ -17,6 +17,7 @@ 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.server.mcp_server._edit_sites import first_call_line
#: Same floor as the direct caller rows, so a hop row is no weaker than they are.
MIN_CALL_CONFIDENCE = 0.7
@@ -82,7 +83,8 @@ async def forwarding_wrapper_callers(
``caller_ids`` are the target's direct callers, best first; wrappers are
expanded in that order. A row has the direct-caller shape plus
- ``via_wrapper`` (the wrapper's symbol id). A wrapper no call edge reaches
+ ``via_wrapper`` (the wrapper's symbol id) and ``call_line`` when the edge
+ records one. A wrapper no call edge reaches
falls back to the files importing it by name or wholesale, shaped like a
file-level caller row (``imports: true``): a dynamic import consumed in a
callback is the usual reason the call itself went unresolved.
@@ -159,6 +161,8 @@ async def forwarding_wrapper_callers(
}
if edge.resolution_origin:
row["via"] = edge.resolution_origin
+ if call_line := first_call_line(edge.call_lines_json):
+ row["call_line"] = call_line
row["via_wrapper"] = wrapper_id
rows.append(row)
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 9205ce35e..b0d127f9f 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
@@ -447,7 +447,13 @@ async def get_answer(
try:
async with get_session(ctx.session_factory) as session:
graph_callers = await caller_evidence(
- session, repo_id, question, question_ids, hits, exclude_spec
+ session,
+ repo_id,
+ question,
+ question_ids,
+ hits,
+ exclude_spec,
+ repo_root=_repo_root(ctx),
)
except Exception:
_log.warning("get_answer: graph caller lookup failed", exc_info=True)
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.py
index f424213a0..7df18727c 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
@@ -10,7 +10,7 @@ question is untouched.
from __future__ import annotations
import re
-from pathlib import PurePosixPath
+from pathlib import Path, PurePosixPath
from typing import Any, NamedTuple
from sqlalchemy import select
@@ -20,6 +20,7 @@ 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
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 (
@@ -172,11 +173,20 @@ async def _retrieved_targets(
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:
+def _row(
+ caller: str,
+ file: str,
+ line: int | None,
+ target: str,
+ edge_type: str,
+ call_line: int | None = None,
+) -> 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
+ if call_line:
+ row["call_line"] = call_line
row["target"] = target
row["edge_type"] = edge_type
return row
@@ -212,6 +222,7 @@ async def caller_evidence(
question_ids: set[str],
hits: list[dict],
exclude_spec: Any = None,
+ repo_root: str | Path | None = None,
) -> CallerEvidence:
"""Graph callers of the symbol a caller question asks about, production first.
@@ -220,7 +231,7 @@ async def caller_evidence(
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.
+ registered. Served call rows carry ``call_line`` and its live ``text``.
"""
if not is_caller_question(question, question_ids):
return NO_EVIDENCE
@@ -258,6 +269,7 @@ async def caller_evidence(
src.start_line if src else None,
target.node_id,
"calls",
+ first_call_line(e.call_lines_json),
)
)
hop = await forwarding_wrapper_callers(
@@ -269,7 +281,12 @@ async def caller_evidence(
continue
seen.add(caller)
row = _row(
- caller, h["file"], h.get("line"), target.node_id, h.get("edge_type") or "imports"
+ caller,
+ h["file"],
+ h.get("line"),
+ target.node_id,
+ h.get("edge_type") or "imports",
+ h.get("call_line"),
)
if h.get("wholesale"):
row["wholesale"] = True
@@ -282,6 +299,10 @@ async def caller_evidence(
row["test"] = True
rows = filter_dicts_by_key(rows, "file", exclude_spec)
rows.sort(key=lambda r: bool(r.get("test")))
+ await attach_call_text(repo_root, rows[:_MAX_ROWS])
+ # Unserved rows are never checked against the live file.
+ for row in rows[_MAX_ROWS:]:
+ row.pop("call_line", None)
return CallerEvidence(rows, named=not cross_file)
@@ -342,7 +363,8 @@ def _short(symbol_id: str) -> str:
def _phrase(row: dict) -> str:
- where = f"{row['file']}:{row['line']}" if row.get("line") is not None else row["file"]
+ 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"])
wrapper = row.get("via_wrapper")
# A same-named caller or wrapper would read "X calls X"; the file tells them apart.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 955c7790d..28d7481d6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -64,6 +64,7 @@ from repowise.server.mcp_server._budget import (
OmissionCollector,
cap_collection,
)
+from repowise.server.mcp_server._edit_sites import attach_call_text, first_call_line
from repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_file
from repowise.server.mcp_server._helpers import (
filter_dicts_by_key,
@@ -192,8 +193,12 @@ async def _resolve_call_graph(
want_callees: bool = False,
exclude_spec: Any = None,
collector: OmissionCollector | None = None,
+ repo_root: Any = None,
) -> None:
- """Resolve callers/callees for a symbol and attach to result_data."""
+ """Resolve callers/callees for a symbol and attach to result_data.
+
+ Served call rows carry ``call_line`` and, read from *repo_root*, its ``text``.
+ """
repo_id = repository.id
# 99.56% of symbols have <=50 callers (p99=31); the rare hub gets an
# explicit `*_truncated` + `*_total` signal below rather than a silent cut.
@@ -334,7 +339,11 @@ async def _resolve_call_graph(
continue
is_call = edge_type == "calls"
if e.target_node_id == node.node_id:
- inbound.append(_entry(e, e.source_node_id, with_edge_type=is_call))
+ row = _entry(e, e.source_node_id, with_edge_type=is_call)
+ # ``line`` is where the caller is defined; this is where it calls.
+ if is_call and (call_line := first_call_line(e.call_lines_json)):
+ row["call_line"] = call_line
+ inbound.append(row)
if e.source_node_id == node.node_id:
outbound.append(_entry(e, e.target_node_id, with_edge_type=is_call))
@@ -383,6 +392,11 @@ async def _resolve_call_graph(
hop = filter_dicts_by_key(hop, "file", exclude_spec)
if hop:
result_data[key] = visible + hop
+ if direction == "in":
+ await attach_call_text(repo_root, result_data[key], node.node_id)
+ # Unserved rows are never checked against the live file.
+ for row in rows[len(visible) :]:
+ row.pop("call_line", None)
continue
if not total:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index cbeb5f98f..fcecfde7b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -1290,6 +1290,7 @@ async def _resolve_one_target(
want_callees=want_callees,
exclude_spec=exclude_spec,
collector=collector,
+ repo_root=repo_root or getattr(repository, "local_path", None),
)
# --- Reference edit set: every live site naming the symbol ---
diff --git a/tests/unit/server/mcp/test_caller_call_text.py b/tests/unit/server/mcp/test_caller_call_text.py
new file mode 100644
index 000000000..33b76fc4e
--- /dev/null
+++ b/tests/unit/server/mcp/test_caller_call_text.py
@@ -0,0 +1,369 @@
+"""Caller rows carry the live source line at the call (``call_line`` + ``text``).
+
+Synthetic graphs in TypeScript, Python and Go over files written to the
+repository root: get_context caller rows (direct and wrapper hop) and
+get_answer ``graph_callers`` rows read the edge's first call line live.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+from repowise.server.mcp_server import _basis
+from repowise.server.mcp_server._edit_sites import MAX_TEXT_CHARS
+from repowise.server.mcp_server.tool_answer import callers
+from repowise.server.mcp_server.tool_context import enrichment
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+
[email protected](autouse=True)
+def _fresh_basis_cache():
+ _basis.reset_cache()
+ yield
+ _basis.reset_cache()
+
+
+def _sym(rid, node_id, *, lines=(1, 30), kind="function", language="typescript"):
+ file_path, _, qual = node_id.partition("::")
+ return GraphNode(
+ id=f"ct_{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, *, call_lines=None, edge_type="calls", names=None):
+ return GraphEdge(
+ id=f"ct_{source}->{target}:{edge_type}",
+ repository_id=rid,
+ source_node_id=source,
+ target_node_id=target,
+ edge_type=edge_type,
+ confidence=0.9,
+ imported_names_json=json.dumps(names or []),
+ call_lines_json=json.dumps(call_lines or []),
+ created_at=_NOW,
+ )
+
+
+def _write(root, rel: str, lines: list[str]) -> None:
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+async def _callers(session, rid, target, root, **kw) -> list[dict]:
+ out: dict = {}
+ await enrichment._resolve_call_graph(
+ session,
+ await session.get(Repository, rid),
+ target,
+ "symbol",
+ out,
+ want_callers=True,
+ repo_root=root,
+ **kw,
+ )
+ return out["callers"]
+
+
+async def test_ts_direct_caller_row_carries_its_call_line(session, populated_db, tmp_path):
+ rid = populated_db
+ _write(tmp_path, "src/diag.ts", ["export function tick() {", " const n = 1;",
+ " prune(n, Date.now()); ", "}"])
+ session.add_all(
+ [
+ _sym(rid, "src/poll.ts::prune", lines=(10, 40)),
+ _sym(rid, "src/diag.ts::tick", lines=(1, 4)),
+ _edge(rid, "src/diag.ts::tick", "src/poll.ts::prune", call_lines=[3]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "src/poll.ts::prune", tmp_path)
+ assert row["line"] == 1
+ assert row["call_line"] == 3
+ assert row["text"] == "prune(n, Date.now());"
+
+
+async def test_python_wrapper_hop_row_carries_its_call_line(session, populated_db, tmp_path):
+ rid = populated_db
+ py = {"language": "python"}
+ _write(tmp_path, "pkg/api.py", ["def load(path):", " return _load_impl(path)"])
+ _write(tmp_path, "app/main.py", ["def run():", " cfg = load('x.toml')", " return cfg"])
+ session.add_all(
+ [
+ _sym(rid, "pkg/core.py::_load_impl", lines=(5, 40), **py),
+ _sym(rid, "pkg/api.py::load", lines=(1, 2), **py),
+ _sym(rid, "app/main.py::run", lines=(1, 3), **py),
+ _edge(rid, "pkg/api.py::load", "pkg/core.py::_load_impl", call_lines=[2]),
+ _edge(rid, "app/main.py::run", "pkg/api.py::load", call_lines=[2]),
+ ]
+ )
+ await session.flush()
+
+ direct, hop = await _callers(session, rid, "pkg/core.py::_load_impl", tmp_path)
+ assert direct["text"] == "return _load_impl(path)"
+ assert hop["via_wrapper"] == "pkg/api.py::load"
+ assert (hop["call_line"], hop["text"]) == (2, "cfg = load('x.toml')")
+
+
+async def test_go_several_call_lines_serve_the_first(session, populated_db, tmp_path):
+ rid = populated_db
+ go = {"language": "go"}
+ _write(tmp_path, "cmd/main.go", ["func main() {", "\tdb := store.Open(a)", "\tlog(db)",
+ "\tstore.Open(b)", "}"])
+ session.add_all(
+ [
+ _sym(rid, "store/db.go::Open", lines=(10, 50), **go),
+ _sym(rid, "cmd/main.go::main", lines=(1, 5), **go),
+ _edge(rid, "cmd/main.go::main", "store/db.go::Open", call_lines=[4, 2]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "store/db.go::Open", tmp_path)
+ assert (row["call_line"], row["text"]) == (2, "db := store.Open(a)")
+
+
+async def test_missing_file_short_file_and_unlined_edge_get_no_text(
+ session, populated_db, tmp_path
+):
+ rid = populated_db
+ _write(tmp_path, "src/short.ts", ["run();"])
+ _write(tmp_path, "src/long.ts", [" run(" + "x" * 400 + ");"])
+ session.add_all(
+ [
+ _sym(rid, "src/lib.ts::run", lines=(1, 20)),
+ _sym(rid, "src/gone.ts::a", lines=(1, 9)),
+ _sym(rid, "src/short.ts::b", lines=(1, 9)),
+ _sym(rid, "src/plain.ts::c", lines=(1, 9)),
+ _sym(rid, "src/long.ts::d", lines=(1, 9)),
+ _edge(rid, "src/gone.ts::a", "src/lib.ts::run", call_lines=[3]),
+ _edge(rid, "src/short.ts::b", "src/lib.ts::run", call_lines=[7]),
+ _edge(rid, "src/plain.ts::c", "src/lib.ts::run"),
+ _edge(rid, "src/long.ts::d", "src/lib.ts::run", call_lines=[1]),
+ ]
+ )
+ await session.flush()
+
+ rows = {r["file"]: r for r in await _callers(session, rid, "src/lib.ts::run", tmp_path)}
+ # An unchecked line is not served, so the row keeps only its definition line.
+ assert "call_line" not in rows["src/gone.ts"] and "text" not in rows["src/gone.ts"]
+ assert "call_line" not in rows["src/short.ts"] and "text" not in rows["src/short.ts"]
+ assert rows["src/gone.ts"]["line"] == 1
+ assert "call_line" not in rows["src/plain.ts"] and "text" not in rows["src/plain.ts"]
+ assert len(rows["src/long.ts"]["text"]) == MAX_TEXT_CHARS
+ assert rows["src/long.ts"]["text"].startswith("run(xxx")
+
+
+ "language, caller_file, lines",
+ [
+ # An edit above the call moved it down two lines since indexing.
+ ("typescript", "src/diag.ts",
+ ["export function tick() {", " const a = 1;", " const b = 2;", " prune(a, b);", "}"]),
+ ("python", "app/diag.py",
+ ["def tick():", " a = 1", " b = 2", " prune(a, b)"]),
+ ],
+)
+async def test_shifted_call_line_is_dropped(
+ session, populated_db, tmp_path, language, caller_file, lines
+):
+ rid = populated_db
+ ext = caller_file.rsplit(".", 1)[1]
+ _write(tmp_path, caller_file, lines)
+ session.add_all(
+ [
+ _sym(rid, f"lib/poll.{ext}::prune", lines=(10, 40), language=language),
+ _sym(rid, f"{caller_file}::tick", lines=(1, 5), language=language),
+ _edge(rid, f"{caller_file}::tick", f"lib/poll.{ext}::prune", call_lines=[2]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, f"lib/poll.{ext}::prune", tmp_path)
+ assert row["line"] == 1
+ assert "call_line" not in row and "text" not in row
+
+
+async def test_call_through_an_import_alias_is_served(session, populated_db, tmp_path):
+ rid = populated_db
+ _write(tmp_path, "src/poll.runtime.ts", [
+ 'import { prune as pruneImpl } from "./poll.js";',
+ "export function prune(...args) {",
+ " return pruneImpl(...args);",
+ "}",
+ ])
+ session.add_all(
+ [
+ _sym(rid, "src/poll.ts::prune", lines=(10, 40)),
+ _sym(rid, "src/poll.runtime.ts::prune", lines=(2, 4)),
+ _edge(rid, "src/poll.runtime.ts::prune", "src/poll.ts::prune", call_lines=[3]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "src/poll.ts::prune", tmp_path)
+ assert (row["call_line"], row["text"]) == (3, "return pruneImpl(...args);")
+
+
+async def test_get_context_without_callers_is_byte_identical(
+ setup_mcp, factory, tmp_path, monkeypatch
+):
+ from repowise.server.mcp_server import get_context
+
+ rid = setup_mcp
+ _write(tmp_path, "src/diag.ts", ["export function tick() {", " prune();", "}"])
+ async with factory() as s:
+ s.add_all(
+ [
+ _sym(rid, "src/poll.ts::prune", lines=(10, 40)),
+ _sym(rid, "src/diag.ts::tick", lines=(1, 3)),
+ _edge(rid, "src/diag.ts::tick", "src/poll.ts::prune", call_lines=[2]),
+ ]
+ )
+ await s.commit()
+
+ def _strip(result: dict) -> str:
+ return json.dumps({k: v for k, v in result.items() if k != "_meta"}, sort_keys=True)
+
+ with_callers = await get_context(targets=["src/poll.ts::prune"], include=["callers"])
+ assert '"text": "prune();"' in json.dumps(with_callers)
+ shown = {
+ str(include): await get_context(targets=["src/diag.ts::tick"], include=include)
+ for include in (None, ["callees"])
+ }
+
+ async def _noop(*_a, **_k):
+ return None
+
+ monkeypatch.setattr(enrichment, "attach_call_text", _noop)
+ monkeypatch.setattr(enrichment, "first_call_line", lambda _raw: None)
+ for include in (None, ["callees"]):
+ without = await get_context(targets=["src/diag.ts::tick"], include=include)
+ assert _strip(shown[str(include)]) == _strip(without)
+
+
+async def test_graph_callers_rows_carry_call_text(session, populated_db, tmp_path):
+ rid = populated_db
+ _write(tmp_path, "src/api/login.ts", ["export async function handleLogin(req) {",
+ " const ok = await verifyToken(req.token);", "}"])
+ _write(tmp_path, "src/auth/tokens.runtime.ts", ["export function checkToken(t) {",
+ " return impl.verifyToken(t);", "}"])
+ _write(tmp_path, "src/jobs/sweep.ts", ["function sweep() {", "", " checkToken(t);", "}"])
+ session.add_all(
+ [
+ _sym(rid, "src/auth/tokens.ts::verifyToken", lines=(12, 40)),
+ _sym(rid, "src/api/login.ts::handleLogin", lines=(1, 3)),
+ _sym(rid, "src/auth/tokens.runtime.ts::checkToken", lines=(1, 3)),
+ _sym(rid, "src/jobs/sweep.ts::sweep", lines=(1, 4)),
+ _edge(rid, "src/api/login.ts::handleLogin", "src/auth/tokens.ts::verifyToken",
+ call_lines=[2]),
+ _edge(rid, "src/auth/tokens.runtime.ts::checkToken",
+ "src/auth/tokens.ts::verifyToken", call_lines=[2]),
+ _edge(rid, "src/jobs/sweep.ts::sweep", "src/auth/tokens.runtime.ts::checkToken",
+ call_lines=[3]),
+ _edge(rid, "src/cli.ts", "src/api/login.ts", edge_type="imports",
+ names=["handleLogin"]),
+ ]
+ )
+ await session.flush()
+
+ ev = await callers.caller_evidence(
+ session, rid, "Who calls verifyToken?", {"verifyToken"}, [], repo_root=tmp_path
+ )
+ rows = {r["caller"]: r for r in ev.rows}
+ login = rows["src/api/login.ts::handleLogin"]
+ assert (login["line"], login["call_line"]) == (1, 2)
+ assert login["text"] == "const ok = await verifyToken(req.token);"
+ hop = rows["src/jobs/sweep.ts::sweep"]
+ assert hop["via_wrapper"] == "src/auth/tokens.runtime.ts::checkToken"
+ assert (hop["call_line"], hop["text"]) == (3, "checkToken(t);")
+ # An importer row names no line, so it carries no text.
+ importer = rows["src/cli.ts"]
+ assert "call_line" not in importer and "text" not in importer
+
+ unrooted = await callers.caller_evidence(
+ session, rid, "Who calls verifyToken?", {"verifyToken"}, []
+ )
+ assert all("text" not in r and "call_line" not in r for r in unrooted.rows)
+ assert "handleLogin (src/api/login.ts:1) calls" in callers.caller_sentence(unrooted.rows)
+
+
+async def test_graph_callers_drop_a_shifted_call_line(session, populated_db, tmp_path):
+ rid = populated_db
+ py = {"language": "python"}
+ _write(tmp_path, "app/views.py", ["def login(req):", " log(req)", "", " check_token(req)"])
+ session.add_all(
+ [
+ _sym(rid, "auth/core.py::check_token", lines=(3, 20), **py),
+ _sym(rid, "app/views.py::login", lines=(1, 4), **py),
+ _edge(rid, "app/views.py::login", "auth/core.py::check_token", call_lines=[2]),
+ ]
+ )
+ await session.flush()
+
+ ev = await callers.caller_evidence(
+ session, rid, "Who calls check_token?", {"check_token"}, [], repo_root=tmp_path
+ )
+ (row,) = ev.rows
+ assert "call_line" not in row and "text" not in row
+ assert callers.caller_sentence(ev.rows).startswith(
+ "From the call graph: login (app/views.py:1) calls check_token"
+ )
+
+
+async def test_get_answer_serves_call_text_on_graph_callers(setup_mcp, factory, tmp_path, monkeypatch):
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ from .test_answer_graph_callers import _patch_retrieval
+
+ rid = setup_mcp
+ _write(tmp_path, "src/api/login.ts", ["export async function handleLogin(req) {",
+ " return verifyToken(req.token);", "}"])
+ 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=(1, 3)),
+ _edge(rid, "src/api/login.ts::handleLogin", "src/auth/tokens.ts::verifyToken",
+ call_lines=[2]),
+ ]
+ )
+ await s.commit()
+ _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?")
+ (row,) = result["graph_callers"]
+ assert (row["line"], row["call_line"]) == (1, 2)
+ assert row["text"] == "return verifyToken(req.token);"
+ # The keyless lead cites the call, not the caller's definition line.
+ assert result["answer"].startswith(
+ "From the call graph: handleLogin (src/api/login.ts:2) calls verifyToken"
+ )