Skip to content

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

fix(mcp): make get_context resolve the symbol ids get_symbol hands out (#1435)

Raghav Chamadiyaf82ebb0d6c28
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 15be87f06..1110d922f 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -188,13 +188,23 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
-| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. |
+| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. Symbol ids take the same `"path/to/file.py::Name"` form `get_symbol` accepts, with the same `::` / `.` / `/` separator normalisation, so an id from either tool works in the other. |
| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens) |
| `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
**Returns per target:** Documentation summary, symbols defined, ownership percentages, freshness score, co-change partners, architectural decisions governing the file. With `include` options: source code, call graph, graph metrics, community membership.
+A file with no indexed symbols (README, config, plain data) gets a
+`docs.file_preview` instead of an empty symbol list: line and character counts,
+plus the heading spine for markdown or the first non-blank lines otherwise.
+Counts and verbatim excerpts only, nothing inferred.
+
+When the symbol half of a `path::Name` target does not resolve but the file
+half does, the reply is that file's card with `resolved_to` naming the file and
+a `note` saying which symbol was not found. The file's symbol list is where the
+correct id is, so this is a partial answer rather than a dead end.
+
**When to use:** Before reading or modifying code. Pass all relevant targets in one call to minimize round-trips. In workspace mode, enriched with cross-repo co-change and contract data.
**Example calls:**
@@ -229,6 +239,7 @@ Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.
| `symbol_id` | string | Yes | One of three forms: `"path/to/file.py::SymbolName"` (canonical, from `get_context`'s symbol list; normalises `::` / `.` / `/` separators across languages), `"path/to/file.py:140-180"` (a live range read, 200 lines max), or an omission ref `"repowise#<12-hex>"` / a pasted whole `[repowise#...]` marker. |
| `query` | string | No | Omission refs only: return just the stored lines matching this regex (or substring). Ignored for symbol ids and range reads. |
| `context_lines` | int | No | Extra source lines before/after the symbol (0-50, default 0) |
+| `depth` | int | No | Follow the call graph outward from this symbol and include what it calls, with bodies (1-3, default 1 = this symbol only). Out-of-range values clamp. |
| `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |
**Returns:** For a symbol id or range: the source (bounded at ~600 lines,
@@ -242,17 +253,30 @@ budget appear in `not_rendered` with a `fetch_with` range read. For an
omission ref: the stored content plus provenance (`source`, `created_at`,
`original_tokens`).
+With `depth` above 1 the response also carries `callee_bodies`: the symbols
+this one calls, transitively, each with its `depth` (hops from the root), its
+source, and a `verified` flag. Every symbol appears once, at the shallowest
+depth it was reached from. Callees past the response budget are listed in
+`not_rendered` with the `fetch_with` range that retrieves them, so a bounded
+walk never looks like a complete one.
+
**When to use:** When you need the body of one function or class: pipe the
`symbol_id` straight from `get_context`'s symbol list. Use the line-range form
for anything that falls between symbols. Or when a response's `_meta.omitted`
lists refs you want back and you have no shell for `repowise expand` (e.g.
Claude Desktop).
+Reach for `depth=2` when you are following a call chain: reading a body,
+finding the next name in it, then fetching that one. The graph already holds
+those edges before the first call, so one `depth=2` call replaces the whole
+sequence of round trips.
+
**Example calls:**
```
get_symbol(symbol_id="src/auth/service.py::AuthService")
get_symbol(symbol_id="src/auth/service.py::login", context_lines=10)
+get_symbol(symbol_id="src/auth/service.py::login", depth=2)
get_symbol(symbol_id="src/auth/service.py:140-180")
get_symbol(symbol_id="repowise#a1b2c3d4e5f6")
get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 4b7b7b14e..7109a5077 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -495,6 +495,31 @@ def _compute_alignment(
# ---------------------------------------------------------------------------
+def read_repo_file_text(repo_root: Path | str | None, file_path: str) -> str | None:
+ """Read a repo-relative file's live text, or None when it cannot be served.
+
+ Refuses any path that resolves outside *repo_root*: several tools serve
+ live bytes for a path that came out of the index, and an index row is not
+ a trust boundary. Decoding is lossy on purpose (``errors="replace"``): a
+ card describing a latin-1 file should degrade to mojibake in one field,
+ rather than failing the whole call.
+
+ Several tool modules still carry their own near-identical copy of this,
+ each with one extra behaviour bolted on (a size ceiling, lines instead of
+ text). Those are left alone here rather than churned, but new callers
+ belong on this one, and a copy that needs a variation should wrap it.
+ """
+ if repo_root is None:
+ return None
+ try:
+ root = Path(str(repo_root))
+ abs_path = (root / file_path).resolve()
+ abs_path.relative_to(root.resolve())
+ return abs_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, ValueError):
+ return None
+
+
def _get_exclude_spec(repo_path: Path | str) -> Any:
"""Compile the repo's exclusion rules into a PathSpec, or None."""
from repowise.core.exclusion import build_exclude_spec
diff --git a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
new file mode 100644
index 000000000..12a875931
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
@@ -0,0 +1,207 @@
+"""Resolve a ``"{file_path}::{Name}"`` target string to WikiSymbol rows.
+
+Both ``get_symbol`` and ``get_context`` accept symbol targets, and an agent
+that reads an id out of one response naturally pastes it into the other. That
+only works if the two agree on what an id *is*, so the parsing, the separator
+normalisation and the lookup ladder live here once rather than once per tool.
+
+Separator normalisation is the load-bearing part. Languages disagree about
+what goes between the segments of a qualified name. Python and TypeScript
+write ``Class.method``, C++ and Rust write ``Class::method``, and some tools
+emit ``Class/method``. The index stores exactly one of those forms, so a
+lookup that matches the caller's string verbatim resolves or misses depending
+on which convention the caller happened to use. Every separator form of a
+name is therefore tried, and only the name is rewritten: file paths are
+matched as given, since ``.`` and ``/`` are meaningful inside them.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import or_, select
+
+from repowise.core.persistence.models import WikiSymbol
+from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
+
+# Separators used between name segments AFTER the file path.
+NAME_SEPARATORS = (".", "::", "/")
+
+
+def parse_symbol_id(symbol_id: str) -> tuple[str | None, str | None]:
+ """Split a ``"{path}::{name}"`` id. Either side may be None if missing.
+
+ Tolerant of double-colons in qualified names like ``"Foo::Bar::baz"`` by
+ splitting on the FIRST ``"::"`` only — the first segment is always the
+ file path. Returns (file_path, name) where name may itself contain ``"::"``
+ for nested qualified forms.
+ """
+ if not symbol_id or "::" not in symbol_id:
+ return symbol_id or None, None
+ file_part, _, name_part = symbol_id.partition("::")
+ return (file_part or None, name_part or None)
+
+
+def name_variants(name: str) -> list[str]:
+ """Generate all separator variants of a qualified name segment.
+
+ Given ``"App.update_template_context"`` we yield the same name with every
+ supported separator between segments, so a DB storing ``"App::method"``
+ still resolves when the caller passed dot-form (or vice versa).
+
+ Operates only on the *name* (post file-path), never on the path itself.
+ """
+ if not name:
+ return []
+ # Split on any of the known separators to get atomic segments.
+ segments = [name]
+ for sep in NAME_SEPARATORS:
+ next_segments: list[str] = []
+ for seg in segments:
+ next_segments.extend(seg.split(sep))
+ segments = next_segments
+ segments = [s for s in segments if s]
+ if not segments:
+ return [name]
+ variants: list[str] = []
+ seen: set[str] = set()
+ for sep in NAME_SEPARATORS:
+ v = sep.join(segments)
+ if v not in seen:
+ seen.add(v)
+ variants.append(v)
+ # Also include the original as-is in case it used a mixed separator.
+ if name not in seen:
+ variants.append(name)
+ return variants
+
+
+def symbol_id_variants(symbol_id: str) -> list[str]:
+ """Generate ``{file_path}::{name_variant}`` for every name separator form."""
+ file_path, name = parse_symbol_id(symbol_id)
+ if not file_path or not name:
+ return [symbol_id]
+ out: list[str] = []
+ seen: set[str] = set()
+ for nv in name_variants(name):
+ sid = f"{file_path}::{nv}"
+ if sid not in seen:
+ seen.add(sid)
+ out.append(sid)
+ if symbol_id not in seen:
+ out.append(symbol_id)
+ return out
+
+
+def bare_name(name: str) -> str:
+ """Return the last name segment regardless of separator style."""
+ tail = name
+ for sep in NAME_SEPARATORS:
+ tail = tail.rsplit(sep, 1)[-1]
+ return tail
+
+
+def order_candidates(rows: list[WikiSymbol], queried_file_path: str | None) -> list[WikiSymbol]:
+ """Deterministically order a candidate list, best match first.
+
+ Priority for the head slot:
+ 1. file_path matches the file_path embedded in the queried symbol_id
+ 2. deterministic tiebreak on the (id) primary key (ascending)
+
+ Ambiguous lookups (len > 1) are NOT collapsed here — the caller decides
+ whether to serve every candidate or just the head. The remainder is
+ ordered by source position for readability.
+ """
+ if len(rows) <= 1:
+ return rows
+
+ def _head_key(r: WikiSymbol) -> tuple:
+ file_match = 0 if (queried_file_path and r.file_path == queried_file_path) else 1
+ return (file_match, r.id or "")
+
+ head = min(rows, key=_head_key)
+ rest = sorted(
+ (r for r in rows if r is not head),
+ key=lambda r: (r.file_path or "", r.start_line or 0, r.id or ""),
+ )
+ return [head, *rest]
+
+
+async def resolve_symbol_rows(session, repo_id: str, symbol_id: str) -> list[WikiSymbol]:
+ """Look up a symbol by id, qualified_name, or bare name.
+
+ Returns every row the first matching lookup stage produced, best match
+ first (see :func:`order_candidates`); ``[]`` when nothing matched. A
+ multi-row result means the id is genuinely ambiguous — overloads,
+ re-exports, conditional defs — and the caller decides how to present that
+ rather than having a guess made for it.
+
+ Language-agnostic: the qualified-name portion of the symbol_id is
+ normalized across ``.``, ``::`` and ``/`` separators before matching, so
+ callers can pass any of ``Class.method``, ``Class::method``, or
+ ``Class/method`` and still resolve. Only the name part is normalized —
+ file paths are never rewritten.
+ """
+ file_path, name = parse_symbol_id(symbol_id)
+
+ # 1. Exact symbol_id — try every separator variant.
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.symbol_id.in_(symbol_id_variants(symbol_id)),
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ return order_candidates(rows, file_path)
+
+ if not name:
+ return []
+
+ variants = name_variants(name)
+
+ # 2. Match on (file_path, qualified_name) across name variants.
+ if file_path:
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == file_path,
+ WikiSymbol.qualified_name.in_(variants),
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ return order_candidates(rows, file_path)
+
+ # 3. Match on (file_path, name) — last segment of qualified name.
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == file_path,
+ WikiSymbol.name == bare_name(name),
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ return order_candidates(rows, file_path)
+
+ # 4. Suffix file-path match — the caller passed a bare filename or partial
+ # path ("answer.py::get_answer") instead of the full indexed path.
+ # Resolve against any file whose path ends with that segment on a "/"
+ # boundary, on the bare leaf name, so a remembered filename is not a
+ # dead end.
+ if file_path and name:
+ esc = escape_like(file_path.strip("/").replace("\\", "/"))
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.name == bare_name(name),
+ or_(
+ WikiSymbol.file_path == file_path.strip("/").replace("\\", "/"),
+ WikiSymbol.file_path.like(f"%/{esc}", escape=LIKE_ESCAPE),
+ ),
+ )
+ )
+ rows = list(res.scalars().all())
+ if rows:
+ return order_candidates(rows, file_path)
+
+ return []
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 efffe9ab9..8f2e78618 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
@@ -769,10 +769,36 @@ def _degraded_payload(
read freshness and health signals from there. The failure path used to
set only the top-level key, so a caller watching ``_meta`` saw a normal
empty answer.
+
+ ``answer`` states what the payload IS rather than being left empty. Only
+ the synthesis step is missing here. Retrieval ran, ranked the corpus and
+ succeeded, and its result is the most useful part of a normal reply. An
+ empty ``answer`` beside it reads as a failed call rather than a partial
+ one, and a reader who takes it at face value discards a working result and
+ starts over. The sentence is assembled from what the payload actually
+ carries, so it can never claim more than it has, and no prose about the
+ question itself is invented, that being precisely the part that needs a
+ provider.
"""
+ served = len(hits)
+ if served:
+ summary = (
+ f"No synthesized prose ({reason}), but retrieval succeeded and this "
+ f"payload is usable: {served} ranked "
+ f"{'hit' if served == 1 else 'hits'} in `retrieval`, the files to open "
+ "in `fallback_targets`, and the wider ranked shortlist in `candidates`. "
+ "Read those rather than starting a fresh search."
+ )
+ else:
+ summary = (
+ f"No synthesized prose ({reason}), and retrieval matched nothing for "
+ "this question. Rephrase with an identifier or path from the codebase, "
+ "or search directly."
+ )
+
return _with_candidates(
{
- "answer": "",
+ "answer": summary,
"citations": [],
"confidence": "low",
"degraded": reason,
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 83db341db..a130cc96e 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
@@ -35,7 +35,9 @@ from repowise.server.mcp_server._helpers import (
filter_dicts_by_key,
filter_path_list,
is_excluded,
+ read_repo_file_text,
)
+from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows
from repowise.server.mcp_server.tool_context.enrichment import (
_resolve_call_graph,
_resolve_community,
@@ -91,10 +93,92 @@ def _synthesize_structural_summary(file_path: str, classes: list[str], functions
more = f" (+{len(functions) - 3} more)" if len(functions) > 3 else ""
parts.append(f"function{'s' if len(functions) > 1 else ''} {head}{more}")
if not parts:
- return f"{name}: empty or non-symbol file"
+ return f"{name}: {_NO_SYMBOL_SUMMARY_SUFFIX}"
return f"{name}: " + "; ".join(parts) + "."
+# The summary a file with no indexed symbols falls back to. Named so the
+# preview block below can recognise its own stub and correct it rather than
+# string-matching the sentence in two places.
+_NO_SYMBOL_SUMMARY_SUFFIX = "empty or non-symbol file"
+
+
+def _preview_summary(file_path: str, preview: dict[str, Any]) -> str:
+ """One truthful line about a symbol-less file, built from its own counts."""
+ name = file_path.rsplit("/", 1)[-1]
+ lines = preview.get("lines", 0)
+ if not lines:
+ return f"{name}: empty file"
+ headings = preview.get("headings")
+ if headings:
+ return f"{name}: {lines}-line document, {len(headings)} headings, no indexed symbols."
+ return f"{name}: {lines} lines, no indexed symbols."
+
+
+# A file with no indexed symbols (README, YAML config, SQL, plain text) used to
+# get a card whose entire content was "<name>: empty or non-symbol file", a
+# reply that restates the filename and answers nothing, so the next move was
+# always a Read or a grep the tool could have saved. These bounds keep the
+# replacement preview cheap enough to stay on by default.
+_PREVIEW_MAX_LINES = 15
+_PREVIEW_MAX_LINE_CHARS = 120
+# Beyond this the file is big enough that a preview would misrepresent it; the
+# counts and the "go Read it" note are the honest reply.
+_PREVIEW_MAX_BYTES = 2_000_000
+
+_MARKDOWN_EXTS = (".md", ".markdown", ".mdx", ".rst")
+
+
+def _outline_lines(text: str, file_path: str) -> tuple[str, list[str]]:
+ """Pick the most informative ~15 lines of a symbol-less file.
+
+ Markdown-ish files get their heading spine, which is a genuine table of
+ contents. Everything else gets its first non-blank, non-comment lines,
+ which for config and data files is where the keys live. Returns the kind of
+ excerpt chosen so the caller can label it truthfully.
+ """
+ lines = text.splitlines()
+ if file_path.lower().endswith(_MARKDOWN_EXTS):
+ headings = [ln.strip() for ln in lines if ln.lstrip().startswith("#")]
+ # An .rst or heading-less .md falls through to the head-lines form
+ # rather than reporting an empty outline.
+ if headings:
+ return "headings", headings[:_PREVIEW_MAX_LINES]
+ head = [ln.rstrip() for ln in lines if ln.strip()]
+ return "head", head[:_PREVIEW_MAX_LINES]
+
+
+def _file_preview(repo_root: Any, file_path: str) -> dict[str, Any] | None:
+ """Cheap, true facts about a file the symbol index has nothing to say about.
+
+ Only counts and verbatim excerpts, nothing inferred. Returns None when the
+ file cannot be read, so the caller keeps its existing behaviour rather than
+ reporting an empty preview as if the file were empty.
+ """
+ text = read_repo_file_text(repo_root, file_path)
+ if text is None:
+ return None
+
+ lines = text.splitlines()
+ preview: dict[str, Any] = {"lines": len(lines), "chars": len(text)}
+ if not text.strip():
+ preview["note"] = "File is empty."
+ return preview
+ if len(text) > _PREVIEW_MAX_BYTES:
+ preview["note"] = "File is too large to preview; Read it directly."
+ return preview
+
+ kind, excerpt = _outline_lines(text, file_path)
+ if excerpt:
+ preview[kind] = [ln[:_PREVIEW_MAX_LINE_CHARS] for ln in excerpt]
+ preview["note"] = (
+ "This file has no indexed symbols, so there is no structural card for "
+ "it. The fields above are counts and verbatim excerpts. Read the file "
+ "for its full content."
+ )
+ return preview
+
+
def _clean_signature(signature: str | None) -> str:
"""Collapse a stored signature onto one line.
@@ -134,6 +218,9 @@ async def _resolve_one_target(
page = await session.get(Page, page_id)
target_type = None
file_path_for_git: str | None = None
+ # Set only when a symbol target resolved through the call graph rather than
+ # the symbol index (index-only mode); carries the fields the node has.
+ graph_symbol: GraphNode | None = None
if page and page.repository_id == repo_id:
target_type = "file"
@@ -202,24 +289,36 @@ async def _resolve_one_target(
if page:
target_type = "module"
else:
- # 3. Try symbol (exact then fuzzy)
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.name == target,
- )
- )
- sym_matches = list(res.scalars().all())
- if not sym_matches:
+ # 3. Try symbol.
+ #
+ # A "{path}::{Name}" target goes through the shared symbol lookup,
+ # the same ladder get_symbol uses, so an id lifted from one tool's
+ # response resolves in the other, in whichever separator style the
+ # caller wrote the qualified part. Matching such a target verbatim
+ # against WikiSymbol.name can only ever miss (a stored name is one
+ # segment, never a path-qualified id), and the ilike below would
+ # then scan for a "%path::Class.method%" substring that no name
+ # column contains. Both rungs are skipped for qualified ids.
+ if "::" in target:
+ sym_matches = await resolve_symbol_rows(session, repo_id, target)
+ else:
res = await session.execute(
- select(WikiSymbol)
- .where(
+ select(WikiSymbol).where(
WikiSymbol.repository_id == repo_id,
- WikiSymbol.name.ilike(f"%{escape_like(target)}%", escape=LIKE_ESCAPE),
+ WikiSymbol.name == target,
)
- .limit(10)
)
sym_matches = list(res.scalars().all())
+ if not sym_matches:
+ res = await session.execute(
+ select(WikiSymbol)
+ .where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.name.ilike(f"%{escape_like(target)}%", escape=LIKE_ESCAPE),
+ )
+ .limit(10)
+ )
+ sym_matches = list(res.scalars().all())
if sym_matches:
target_type = "symbol"
file_path_for_git = sym_matches[0].file_path
@@ -238,7 +337,14 @@ async def _resolve_one_target(
file_path_for_git = target
if target_type is None:
- # Fallback 1: index-only mode (no wiki pages) — return graph node + symbols if present
+ # Fallback 1: index-only mode (no wiki pages). Return the graph node.
+ #
+ # The call graph keys its symbol nodes as "{path}::{Class}::{method}",
+ # so a symbol target with no WikiSymbol row matches here, and used to
+ # be typed as a *file*. The card then looked up symbols whose file_path
+ # was the whole id, found none, and reported the symbol as an "empty or
+ # non-symbol file". Type the node by what it is instead: a symbol node
+ # is a symbol target, and its file is the node's file, not its id.
res = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repo_id,
@@ -246,7 +352,12 @@ async def _resolve_one_target(
)
)
gnode = res.scalar_one_or_none()
- if gnode is not None:
+ if gnode is not None and gnode.node_type == "symbol":
+ target_type = "symbol"
+ graph_symbol = gnode
+ file_path_for_git = gnode.file_path
+ page = None
+ elif gnode is not None:
target_type = "file"
file_path_for_git = target
page = None # no wiki page; subsequent blocks must guard for this
@@ -300,6 +411,36 @@ async def _resolve_one_target(
"suggestions": module_paths,
}
+ # Fallback 2c: a "{path}::{Name}" target whose symbol half did not
+ # resolve, but whose file half is a real indexed file. The caller asked
+ # about something *in* that file, so the file's card is a partial answer
+ # and a strictly better reply than "not found": it carries the symbol
+ # list, which is where the correct id was going to come from anyway.
+ # Reported as ``resolved_to`` so the degrade is legible rather than
+ # looking like the symbol was found.
+ if target_type is None and "::" in target:
+ file_part = target.split("::", 1)[0]
+ if file_part and file_part != target and not is_excluded(file_part, exclude_spec):
+ # file_part contains no "::", so this recursion is depth-1.
+ card = await _resolve_one_target(
+ session,
+ repository,
+ file_part,
+ include,
+ compact,
+ exclude_spec=exclude_spec,
+ repo_root=repo_root,
+ )
+ if "error" not in card:
+ card["target"] = target
+ card["resolved_to"] = file_part
+ card["note"] = (
+ f"No symbol matched {target.split('::', 1)[1]!r} in this file; "
+ f"showing the card for {file_part!r} instead. Pick the symbol "
+ "you meant from the symbol list."
+ )
+ return card
+
# Fallback 3: fuzzy path suggestions — match by filename or partial path.
# Only runs if the prior fallbacks didn't resolve the target.
if target_type is None:
@@ -498,6 +639,22 @@ async def _resolve_one_target(
"label": _cmeta.get("label", ""),
}
+ # A file the symbol index has nothing for still exists and still has
+ # content. Serving counts and a verbatim excerpt costs one read and
+ # answers the "what is in here" the caller was asking; the card
+ # without it restates the filename. Applies to all three shapes
+ # above; none of them has anything to say about a symbol-less file.
+ if not symbols:
+ preview = _file_preview(repo_root, target)
+ if preview is not None:
+ docs["file_preview"] = preview
+ # "empty or non-symbol file" is the only summary a
+ # symbol-less file could get, and next to a preview showing
+ # 800 lines of headings it is simply false. Restate it from
+ # what the preview actually counted.
+ if docs.get("summary", "").endswith(_NO_SYMBOL_SUMMARY_SUFFIX):
+ docs["summary"] = _preview_summary(target, preview)
+
elif target_type == "module":
docs["title"] = page.title
docs["summary"] = page.summary or ""
@@ -560,13 +717,21 @@ async def _resolve_one_target(
)
elif target_type == "symbol":
- sym = sym_matches[0] # type: ignore[possibly-undefined]
+ # In index-only mode the symbol may exist as a graph node with no
+ # WikiSymbol row, so the node carries the fields it has and the
+ # rest are simply absent rather than faked.
+ sym = sym_matches[0] if sym_matches else graph_symbol # type: ignore[possibly-undefined]
docs["name"] = sym.name
- docs["qualified_name"] = sym.qualified_name
docs["kind"] = sym.kind
- docs["signature"] = _clean_signature(sym.signature)
docs["file_path"] = sym.file_path
- docs["docstring"] = sym.docstring or ""
+ for attr, key in (
+ ("qualified_name", "qualified_name"),
+ ("signature", "signature"),
+ ("docstring", "docstring"),
+ ):
+ value = getattr(sym, attr, None)
+ if value:
+ docs[key] = _clean_signature(value) if attr == "signature" else value
# File page summary (full content gated behind include=["full_doc"])
sym_page_id = f"file_page:{sym.file_path}"
sym_page = await session.get(Page, sym_page_id)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index f636a99af..adfee5041 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -48,7 +48,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
-from sqlalchemy import or_, select
+from sqlalchemy import select
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import WikiSymbol
@@ -59,9 +59,19 @@ from repowise.server.mcp_server._helpers import (
_resolve_repo_context,
_unsupported_repo_all,
is_excluded,
+ read_repo_file_text,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
+from repowise.server.mcp_server._symbol_lookup import (
+ NAME_SEPARATORS,
+ bare_name,
+ name_variants,
+ order_candidates,
+ parse_symbol_id,
+ resolve_symbol_rows,
+ symbol_id_variants,
+)
from repowise.server.mcp_server._verify import check_symbol_bounds, heal_symbol_row
_log = __import__("logging").getLogger("repowise.mcp.symbol")
@@ -103,6 +113,153 @@ _MAX_FALLBACK_MATCHES = 8
_AMBIGUITY_CHAR_BUDGET = 20_000
+# Callee expansion. A symbol whose body names the next symbol you need is the
+# common case, and fetching that next one is a fresh round trip: the chain gets
+# walked a hop at a time, each hop a full request/response, when the graph
+# already knows every edge. ``depth`` serves the reachable bodies together.
+#
+# Depth is capped low on purpose. Fan-out compounds, so depth 3 on a hub symbol
+# is a payload nobody asked for; the observed hand-walks are chains, not trees,
+# and are covered well before the cap.
+_MAX_CALLEE_DEPTH = 3
+# Total chars of callee source served. Sized against the symbol cap above: a
+# handful of ordinary bodies, and a hub is truncated rather than serialised.
+_CALLEE_CHAR_BUDGET = 24_000
+# Per-hop fan-out cap, applied before any body is read.
+_MAX_CALLEES_PER_HOP = 12
+# Callee bodies are context for the root symbol, not the subject of the call,
+# so they are bounded tighter than the root's ~600.
+_MAX_CALLEE_BODY_LINES = 150
+
+
+async def _expand_callees(
+ session,
+ repo_id: str,
+ root_row: WikiSymbol,
+ repo_root: Path,
+ depth: int,
+ exclude_spec: Any,
+) -> dict[str, Any] | None:
+ """Breadth-first walk of the call graph from *root_row*, bodies included.
+
+ Symbol graph nodes are keyed by the same ``"{path}::{Name}"`` string as
+ ``WikiSymbol.symbol_id``, so each hop is one edge query plus one row query
+ regardless of fan-out. Every symbol is served at most once and at the
+ shallowest depth it was reached from, which keeps a diamond in the call
+ graph from being serialised twice.
+
+ Returns None when the root has no outbound call edges, so the caller adds
+ no empty block to an ordinary response.
+ """
+ from repowise.core.persistence.crud import get_graph_edges_for_node
+ from repowise.server.mcp_server.tool_context.enrichment import (
+ _CALL_EDGE_TYPES,
+ _MIN_CALL_CONFIDENCE,
+ )
+
+ seen: set[str] = {root_row.symbol_id}
+ frontier = [root_row.symbol_id]
+ entries: list[dict[str, Any]] = []
+ omitted: list[dict[str, Any]] = []
+ text_cache: dict[str, str | None] = {}
+ remaining = _CALLEE_CHAR_BUDGET
+
+ for hop in range(1, depth):
+ if not frontier:
+ break
+ next_ids: list[str] = []
+ for node_id in frontier:
+ edges = await get_graph_edges_for_node(
+ session,
+ repo_id,
+ node_id,
+ direction="callees",
+ edge_types=_CALL_EDGE_TYPES,
+ limit=_MAX_CALLEES_PER_HOP,
+ )
+ for e in edges:
+ if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:
+ continue
+ if e.target_node_id not in seen:
+ seen.add(e.target_node_id)
+ next_ids.append(e.target_node_id)
+ if not next_ids:
+ break
+
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.symbol_id.in_(next_ids),
+ )
+ )
+ rows = [r for r in res.scalars().all() if not is_excluded(r.file_path, exclude_spec)]
+ # Stable order so the same call returns the same payload twice.
+ rows.sort(key=lambda r: (r.file_path or "", r.start_line or 0, r.symbol_id or ""))
+
+ for row in rows:
+ entry: dict[str, Any] = {
+ "symbol_id": row.symbol_id,
+ "name": row.name,
+ "file": row.file_path,
+ "kind": row.kind,
+ "signature": _clean_symbol_signature(row.signature),
+ "depth": hop,
+ }
+ if row.file_path not in text_cache:
+ text_cache[row.file_path] = _read_file_text(repo_root, row.file_path)
+ text = text_cache[row.file_path]
+ if text is None:
+ entry["note"] = "source file could not be read"
+ omitted.append(entry)
+ continue
+
+ # Bounds are checked so ``verified`` is honest, but a correction is
+ # not written back here: healing belongs to the read that asked for
+ # the symbol, not to a neighbour swept up by a graph walk.
+ check = check_symbol_bounds(row, text)
+ source, start, end, _total = _slice_text(
+ text, check.start_line, check.end_line, 0, max_lines=_MAX_CALLEE_BODY_LINES
+ )
+ numbered = _number_lines(source, start)
+ if len(numbered) > remaining:
+ # Out of budget: name the read that fetches it rather than
+ # dropping the symbol silently.
+ entry["fetch_with"] = f"{row.file_path}:{check.start_line}-{check.end_line}"
+ omitted.append(entry)
+ continue
+ remaining -= len(numbered)
+ entry.update(
+ {
+ "start_line": start,
+ "end_line": end,
+ "source": numbered,
+ "verified": check.verified,
+ }
+ )
+ if end < check.end_line:
+ entry["truncated"] = True
+ entry["continuation"] = f"{row.file_path}:{end + 1}-{check.end_line}"
+ entries.append(entry)
+
+ frontier = next_ids
+
+ if not entries and not omitted:
+ return None
+ block: dict[str, Any] = {"depth": depth, "callees": entries}
+ if omitted:
+ block["not_rendered"] = omitted
+ block["note"] = (
+ "Callees past the response budget are listed in not_rendered; "
+ "fetch one with its fetch_with range."
+ )
+ return block
+
+
+def _clean_symbol_signature(signature: str | None) -> str:
+ """Collapse a stored signature onto one line (CRLF indices keep the \\r\\n)."""
+ return " ".join((signature or "").split())
+
+
def _extract_omission_ref(symbol_id: str) -> str | None:
"""Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""
candidate = symbol_id.strip()
@@ -285,198 +442,16 @@ def _live_grep_fallback(repo_root: Path, file_path: str, name: str) -> list[dict
return matches
-def _parse_symbol_id(symbol_id: str) -> tuple[str | None, str | None]:
- """Split a "{path}::{name}" id. Either side may be None if missing.
-
- Tolerant of double-colons in qualified names like "Foo::Bar::baz" by
- splitting on the FIRST "::" only — the first segment is always the file
- path. Returns (file_path, name) where name may itself contain "::" for
- nested qualified forms ("Class::method").
- """
- if not symbol_id or "::" not in symbol_id:
- return symbol_id or None, None
- file_part, _, name_part = symbol_id.partition("::")
- return (file_part or None, name_part or None)
-
-
-# Separators used between name segments AFTER the file path. Different
-# languages use different conventions: Python/TS/Go use ".", C++/Rust use
-# "::", and some tools emit "/". The lookup must be uniform across all of
-# them — we never encode a single language's rule.
-_NAME_SEPARATORS = (".", "::", "/")
-
-
-def _name_variants(name: str) -> list[str]:
- """Generate all separator variants of a qualified name segment.
-
- Given "App.update_template_context" we yield the same name with every
- supported separator between segments, so a DB storing "App::method"
- still resolves when the agent passed dot-form (or vice versa).
-
- Operates only on the *name* (post file-path), never on the path itself.
- """
- if not name:
- return []
- # Split on any of the known separators to get atomic segments.
- segments = [name]
- for sep in _NAME_SEPARATORS:
- next_segments: list[str] = []
- for seg in segments:
- next_segments.extend(seg.split(sep))
- segments = next_segments
- segments = [s for s in segments if s]
- if not segments:
- return [name]
- variants: list[str] = []
- seen: set[str] = set()
- for sep in _NAME_SEPARATORS:
- v = sep.join(segments)
- if v not in seen:
- seen.add(v)
- variants.append(v)
- # Also include the original as-is in case it used a mixed separator.
- if name not in seen:
- variants.append(name)
- return variants
-
-
-def _symbol_id_variants(symbol_id: str) -> list[str]:
- """Generate {file_path}::{name_variant} for every name separator form."""
- file_path, name = _parse_symbol_id(symbol_id)
- if not file_path or not name:
- return [symbol_id]
- out: list[str] = []
- seen: set[str] = set()
- for nv in _name_variants(name):
- sid = f"{file_path}::{nv}"
- if sid not in seen:
- seen.add(sid)
- out.append(sid)
- if symbol_id not in seen:
- out.append(symbol_id)
- return out
-
-
-def _bare_name(name: str) -> str:
- """Return the last name segment regardless of separator style."""
- tail = name
- for sep in _NAME_SEPARATORS:
- tail = tail.rsplit(sep, 1)[-1]
- return tail
-
-
-def _order_candidates(rows: list[WikiSymbol], queried_file_path: str | None) -> list[WikiSymbol]:
- """Deterministically order a candidate list, best match first.
-
- Priority for the head slot:
- 1. file_path matches the file_path embedded in the queried symbol_id
- 2. deterministic tiebreak on the (id) primary key (ascending)
-
- Ambiguous lookups (len > 1) are NOT collapsed here — get_symbol serves
- every candidate so the agent, not a heuristic, decides which one it
- meant. The remainder is ordered by source position for readability.
- """
- if len(rows) <= 1:
- return rows
-
- def _head_key(r: WikiSymbol) -> tuple:
- file_match = 0 if (queried_file_path and r.file_path == queried_file_path) else 1
- return (file_match, r.id or "")
-
- head = min(rows, key=_head_key)
- rest = sorted(
- (r for r in rows if r is not head),
- key=lambda r: (r.file_path or "", r.start_line or 0, r.id or ""),
- )
- return [head, *rest]
-
-
-async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> list[WikiSymbol]:
- """Look up a symbol by id, qualified_name, or bare name.
-
- Returns every row the first matching lookup stage produced, best match
- first (see :func:`_order_candidates`); ``[]`` when nothing matched.
- A multi-row result means the id is genuinely ambiguous — overloads,
- re-exports, conditional defs — and the caller serves ALL of them rather
- than guessing (a wrong silent pick triggers a read-spiral).
-
- Language-agnostic: the qualified-name portion of the symbol_id is
- normalized across ``.``, ``::`` and ``/`` separators before matching,
- so callers can pass any of ``Class.method``, ``Class::method``, or
- ``Class/method`` and still resolve. Only the name part is normalized —
- file paths are never rewritten.
- """
- file_path, _name = _parse_symbol_id(symbol_id)
- variants = _symbol_id_variants(symbol_id)
-
- # 1. Exact symbol_id — try every separator variant.
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.symbol_id.in_(variants),
- )
- )
- rows = list(res.scalars().all())
- if rows:
- return _order_candidates(rows, file_path)
-
- _, name = _parse_symbol_id(symbol_id)
- if not name:
- return []
-
- name_variants = _name_variants(name)
-
- # 2. Match on (file_path, qualified_name) across name variants.
- if file_path:
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.file_path == file_path,
- WikiSymbol.qualified_name.in_(name_variants),
- )
- )
- rows = list(res.scalars().all())
- if rows:
- return _order_candidates(rows, file_path)
-
- # 3. Match on (file_path, name) — last segment of qualified name.
- bare = _bare_name(name)
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.file_path == file_path,
- WikiSymbol.name == bare,
- )
- )
- rows = list(res.scalars().all())
- if rows:
- return _order_candidates(rows, file_path)
-
- # 4. Suffix file-path match — the caller passed a bare filename or partial
- # path ("answer.py::get_answer") instead of the full indexed path.
- # Resolve against any file whose path ends with that segment on a "/"
- # boundary, on the bare leaf name. Mirrors get_context's basename ladder
- # so both tools accept the same shorthand instead of a dead "not found".
- if file_path and name:
- from repowise.server.mcp_server._helpers import LIKE_ESCAPE, escape_like
-
- esc = escape_like(file_path.strip("/").replace("\\", "/"))
- bare = _bare_name(name)
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.name == bare,
- or_(
- WikiSymbol.file_path == file_path.strip("/").replace("\\", "/"),
- WikiSymbol.file_path.like(f"%/{esc}", escape=LIKE_ESCAPE),
- ),
- )
- )
- rows = list(res.scalars().all())
- if rows:
- return _order_candidates(rows, file_path)
-
- return []
+# The symbol-id grammar, separator normalisation and lookup ladder are shared
+# with get_context (see _symbol_lookup for why they cannot diverge). Re-exported
+# under the module-private names this file has always used.
+_NAME_SEPARATORS = NAME_SEPARATORS
+_parse_symbol_id = parse_symbol_id
+_name_variants = name_variants
+_symbol_id_variants = symbol_id_variants
+_bare_name = bare_name
+_order_candidates = order_candidates
+_resolve_symbol = resolve_symbol_rows
async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spec) -> list[str]:
@@ -509,19 +484,10 @@ async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spe
def _read_file_text(repo_path: Path, file_path: str) -> str | None:
"""Read a repo file's live text, or None when unreadable/outside the root."""
- abs_path = (repo_path / file_path).resolve()
- # Defense in depth: never read outside the repo root, even if the
- # WikiSymbol.file_path was somehow tampered with.
- try:
- abs_path.relative_to(repo_path.resolve())
- except ValueError:
- _log.warning("get_symbol path escape attempt: %s", file_path)
- return None
- try:
- return abs_path.read_text(encoding="utf-8", errors="replace")
- except OSError as exc:
- _log.warning("get_symbol read failed for %s: %s", abs_path, exc)
- return None
+ text = read_repo_file_text(repo_path, file_path)
+ if text is None:
+ _log.warning("get_symbol could not serve %s (unreadable or outside repo root)", file_path)
+ return text
def _slice_text(
@@ -661,6 +627,7 @@ async def get_symbol(
repo: str | None = None,
query: str | None = None,
id: str | None = None,
+ depth: int = 1,
) -> dict:
"""Follow-up read of one symbol whose id another response already gave you.
@@ -674,11 +641,11 @@ async def get_symbol(
``verified: true`` = bounds checked (or corrected) against the live file:
no follow-up Read needed. ``bounds: "approximate"`` = the symbol moved and
re-location failed. An ambiguous id (overloads, re-exports) returns ALL
- matching bodies in ``candidates`` — none is silently chosen. Also serves
+ matching bodies in ``candidates``; none is silently chosen. Also serves
live range reads ("path.py:140-180", ≤200 lines, always verified) and
- omission refs ("repowise#<12-hex>"). Index misses grep the live file and
- return fallback_lines instead of a dead end. When ``truncated`` is true the
- response carries a ``continuation`` token — the exact range read that
+ omission refs ("repowise#<12-hex>"). An index miss returns fallback_lines
+ from a live grep rather than a dead end. When ``truncated`` is true the
+ response carries a ``continuation`` token: the exact range read that
fetches the remainder; pass it straight back to get_symbol.
Args:
@@ -686,8 +653,10 @@ async def get_symbol(
live range, or an omission ref.
context_lines: extra lines before/after (0-50).
repo: usually omitted.
- query: omission refs only — regex/substring filter on lines.
+ query: omission refs only, regex/substring filter on lines.
id: accepted alias for ``symbol_id``.
+ depth: 1 (default) is this symbol alone; 2-3 also returns the bodies
+ it calls, transitively, in ``callee_bodies``.
"""
if repo == "all":
return _unsupported_repo_all("get_symbol")
@@ -732,6 +701,9 @@ async def get_symbol(
# Bound context_lines to a sane range — runaway values would
# defeat the whole point of symbol-level retrieval.
context_lines = max(0, min(50, context_lines))
+ # Clamp rather than reject: an out-of-range depth is a caller reaching for
+ # more of the chain, and the useful reply is the deepest walk we will do.
+ depth = max(1, min(_MAX_CALLEE_DEPTH, depth))
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
@@ -890,6 +862,14 @@ async def get_symbol(
"the indexed line range from the current file contents; verify "
"before citing."
)
+ if depth > 1:
+ async with get_session(ctx.session_factory) as session:
+ callee_block = await _expand_callees(
+ session, repository.id, row, repo_root, depth, exclude_spec
+ )
+ if callee_block is not None:
+ response["callee_bodies"] = callee_block
+
# Declare the exact counterfactual: serving one symbol replaced Reading the
# whole file. The savings instrumentation prefers this over its estimator.
from repowise.server.mcp_server._savings import declare_replaced
diff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
index e63b3cdee..7d9bd42d3 100644
--- a/tests/unit/server/mcp/test_answer_synthesis_timeout.py
+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
@@ -407,8 +407,43 @@ def test_both_failure_modes_return_the_same_payload_shape(reason):
def test_degraded_payload_still_hands_back_usable_retrieval():
"""Retrieval succeeded; losing it too would waste the work already done."""
payload = _payload()
- assert payload["answer"] == ""
assert payload["confidence"] == "low"
assert payload["fallback_targets"] == ["pkg/mod.py"]
assert len(payload["retrieval"]) == 1
assert payload["retrieval"][0]["path"] == "pkg/mod.py"
+
+
+def test_degraded_answer_describes_the_payload_instead_of_being_empty():
+ """An empty ``answer`` beside working retrieval reads as a failed call.
+
+ The field is the first thing a reader looks at, so leaving it blank while
+ ``retrieval``/``candidates`` are populated invites throwing the whole
+ result away. It must name what survived and where to find it.
+ """
+ payload = _payload()
+ answer = payload["answer"]
+ assert answer, "degraded answer must not be empty"
+ assert "synthesis-failed" in answer, "the reason belongs in the visible field"
+ for field in ("retrieval", "fallback_targets", "candidates"):
+ assert field in answer, f"{field} is populated but never mentioned"
+
+
+def test_degraded_answer_does_not_promise_hits_it_does_not_have():
+ """The other direction: no hits must not produce a 'this is usable' claim.
+
+ A sentence assembled from a template rather than from the payload would
+ advertise ranked hits on an empty retrieval, which is the failure mode that
+ would make the wording worse than the blank field it replaced.
+ """
+ payload = _degraded_payload(
+ reason="no-llm-provider",
+ note="DEGRADED",
+ hits=[],
+ fallback_targets=[],
+ repository=None,
+ t0=0.0,
+ )
+ answer = payload["answer"]
+ assert answer
+ assert "matched nothing" in answer
+ assert "ranked hit" not in answer
diff --git a/tests/unit/server/mcp/test_context_file_preview.py b/tests/unit/server/mcp/test_context_file_preview.py
new file mode 100644
index 000000000..a78728485
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_file_preview.py
@@ -0,0 +1,172 @@
+"""A file with no indexed symbols must still be described, not just named.
+
+The card for a README used to be, in full, its own filename plus "empty or
+non-symbol file". That answers strictly less than the question it was asked,
+and the only move left is the Read the tool was called to avoid. These tests
+pin the replacement to facts that are cheap and checkable. The harder half is
+pinning it against overclaiming on files it cannot actually preview.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import GitMetadata, GraphNode, Repository
+from repowise.server.mcp_server.tool_context.targets import _file_preview, _resolve_one_target
+
+_NON_CODE = "docs/guide.md"
+
+
+async def repository(session, populated_db) -> Repository:
+ return await session.get(Repository, populated_db)
+
+
+async def symbolless_file(session, populated_db, tmp_path):
+ """A real on-disk file indexed as a graph node, with no symbols.
+
+ This is the shape a README actually has: a file node in the graph, no
+ wiki page (too few symbols to earn one), and nothing in WikiSymbol, so
+ the card falls to the index-only rung and had nothing to put in it.
+ """
+ session.add(
+ GraphNode(
+ id="gn-guide",
+ repository_id=populated_db,
+ node_id=_NON_CODE,
+ node_type="file",
+ language="markdown",
+ symbol_count=0,
+ )
+ )
+ session.add(
+ GitMetadata(
+ id="gm-guide",
+ repository_id=populated_db,
+ file_path=_NON_CODE,
+ commit_count_total=1,
+ commit_count_90d=0,
+ commit_count_30d=0,
+ top_authors_json="[]",
+ significant_commits_json="[]",
+ co_change_partners_json="[]",
+ is_hotspot=False,
+ is_stable=True,
+ )
+ )
+ await session.flush()
+ doc = tmp_path / "docs"
+ doc.mkdir()
+ (doc / "guide.md").write_text(
+ "# Guide\n\nIntro prose.\n\n## Install\n\nrun it\n\n## Usage\n\nuse it\n",
+ encoding="utf-8",
+ )
+ return tmp_path
+
+
+# --- the preview helper, in isolation --------------------------------------
+
+
+def test_markdown_preview_returns_the_heading_spine(tmp_path) -> None:
+ """Headings are a real table of contents: the cheapest true summary."""
+ (tmp_path / "r.md").write_text("# Title\n\nbody\n\n## One\n\nmore\n\n## Two\n", encoding="utf-8")
+ preview = _file_preview(tmp_path, "r.md")
+ assert preview["headings"] == ["# Title", "## One", "## Two"]
+ assert preview["lines"] > 0
+ assert preview["chars"] > 0
+
+
+def test_non_markdown_preview_returns_head_lines(tmp_path) -> None:
+ """Config and data files keep their keys at the top, so head lines carry them."""
+ (tmp_path / "c.yaml").write_text("\n\nname: svc\nport: 8080\n", encoding="utf-8")
+ preview = _file_preview(tmp_path, "c.yaml")
+ assert preview["head"] == ["name: svc", "port: 8080"]
+ assert "headings" not in preview
+
+
+def test_headingless_markdown_falls_back_to_head_lines(tmp_path) -> None:
+ """An .md with no '#' must not report an empty outline as its content."""
+ (tmp_path / "plain.md").write_text("just prose\nand more prose\n", encoding="utf-8")
+ preview = _file_preview(tmp_path, "plain.md")
+ assert preview["head"] == ["just prose", "and more prose"]
+ assert "headings" not in preview
+
+
+def test_empty_file_is_reported_as_empty_not_previewed(tmp_path) -> None:
+ """The one case where "empty" is the true answer must still say so."""
+ (tmp_path / "e.md").write_text("", encoding="utf-8")
+ preview = _file_preview(tmp_path, "e.md")
+ assert preview["lines"] == 0
+ assert preview["note"] == "File is empty."
+ assert "headings" not in preview and "head" not in preview
+
+
+def test_unreadable_file_yields_no_preview_rather_than_an_empty_one(tmp_path) -> None:
+ """The failure direction: a file we cannot read is not a file with no content.
+
+ Returning a zero-count preview here would state something false about the
+ file; returning None leaves the card exactly as it was.
+ """
+ assert _file_preview(tmp_path, "does/not/exist.md") is None
+
+
+def test_preview_refuses_to_escape_the_repo_root(tmp_path) -> None:
+ """A path from the index is not a trust boundary."""
+ outside = tmp_path.parent / "outside-secret.md"
+ outside.write_text("# secret\n", encoding="utf-8")
+ root = tmp_path / "root"
+ root.mkdir()
+ assert _file_preview(root, "../outside-secret.md") is None
+
+
+def test_long_lines_are_capped(tmp_path) -> None:
+ """A minified file must not blow the card up through the preview."""
+ (tmp_path / "big.txt").write_text("x" * 5000 + "\n", encoding="utf-8")
+ preview = _file_preview(tmp_path, "big.txt")
+ assert len(preview["head"][0]) == 120
+
+
+# --- the preview in the card -----------------------------------------------
+
+
+async def test_symbolless_file_card_carries_a_preview(
+ session, repository, symbolless_file
+) -> None:
+ """End to end: the card answers "what is in this file" without a Read."""
+ card = await _resolve_one_target(
+ session,
+ repository,
+ _NON_CODE,
+ None,
+ True,
+ exclude_spec=None,
+ repo_root=symbolless_file,
+ )
+ preview = card["docs"]["file_preview"]
+ assert preview["headings"] == ["# Guide", "## Install", "## Usage"]
+ assert preview["lines"] == 11
+ assert "Read the file" in preview["note"]
+ # The stub summary contradicted the preview sitting beside it.
+ summary = card["docs"]["summary"]
+ assert "empty or non-symbol file" not in summary
+ assert "11" in summary and "3 headings" in summary
+
+
+async def test_file_with_symbols_gets_no_preview(session, repository, tmp_path) -> None:
+ """The other direction: the preview must not displace a real symbol card.
+
+ ``src/auth/service.py`` has indexed symbols, so its card already answers
+ the question and a preview would be redundant bytes on every code file.
+ """
+ card = await _resolve_one_target(
+ session,
+ repository,
+ "src/auth/service.py",
+ None,
+ True,
+ exclude_spec=None,
+ repo_root=tmp_path,
+ )
+ assert card["docs"]["symbols"]
+ assert "file_preview" not in card["docs"]
diff --git a/tests/unit/server/mcp/test_context_symbol_targets.py b/tests/unit/server/mcp/test_context_symbol_targets.py
new file mode 100644
index 000000000..7071a2f29
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_symbol_targets.py
@@ -0,0 +1,210 @@
+"""get_context must resolve the symbol ids get_symbol hands out.
+
+Two tools, one id vocabulary. An agent reads a ``symbol_id`` out of one
+response and pastes it into the other; if only one of them understands the
+string, the id looks broken rather than the tool. These tests pin the three
+ways that went wrong:
+
+* a qualified target written with a different separator than the index stores
+* a symbol-shaped target being typed as a *file* by the graph-node fallback,
+ which produced a confident card describing the symbol as an empty file
+* an unresolvable symbol half throwing away the resolvable file half
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
+from repowise.server.mcp_server.tool_context.targets import _resolve_one_target
+
+_FILE = "src/auth/service.py"
+
+
+async def repository(session, populated_db) -> Repository:
+ return await session.get(Repository, populated_db)
+
+
+async def _card(session, repository, target, *, repo_root=None) -> dict:
+ return await _resolve_one_target(
+ session, repository, target, None, True, exclude_spec=None, repo_root=repo_root
+ )
+
+
+# --- separator normalisation, both directions ------------------------------
+
+
+ "target",
+ [
+ f"{_FILE}::AuthService.login",
+ f"{_FILE}::AuthService::login",
+ f"{_FILE}::AuthService/login",
+ ],
+)
+async def test_qualified_symbol_resolves_in_every_separator_style(
+ session, repository, target
+) -> None:
+ """Class.method, Class::method and Class/method are the same symbol.
+
+ The fixture stores this symbol as ``src/auth/service.py::login`` with a
+ dotted ``qualified_name``, so none of these three targets matches the
+ index verbatim. Which one a caller writes is a fact about their language,
+ not about the codebase, and must not decide whether the lookup works.
+ """
+ card = await _card(session, repository, target)
+ assert "error" not in card, card.get("error")
+ assert card["type"] == "symbol"
+ assert card["docs"]["name"] == "login"
+ assert card["docs"]["file_path"] == _FILE
+
+
+async def test_dot_and_colon_forms_return_the_same_card(session, repository) -> None:
+ """The stronger claim: not merely 'both work' but 'both agree'."""
+ dot = await _card(session, repository, f"{_FILE}::AuthService.login")
+ colon = await _card(session, repository, f"{_FILE}::AuthService::login")
+ # ``target`` echoes the caller's string by design; everything describing
+ # the resolved symbol must be identical.
+ assert dot["docs"] == colon["docs"]
+ assert dot["type"] == colon["type"] == "symbol"
+
+
+async def test_bare_symbol_name_still_resolves(session, repository) -> None:
+ """The unqualified rung is untouched; qualified handling is additive."""
+ card = await _card(session, repository, "AuthService")
+ assert card["type"] == "symbol"
+ assert card["docs"]["name"] == "AuthService"
+
+
+# --- the other direction: a real miss must still be a miss -----------------
+
+
+async def test_absent_symbol_in_an_absent_file_still_errors(session, repository) -> None:
+ """Normalisation must not turn every string into a hit.
+
+ Nothing about this target exists, so the tool has nothing to degrade to
+ and must say so rather than inventing a card.
+ """
+ card = await _card(session, repository, "src/nope/missing.py::Ghost")
+ assert "error" in card
+ assert "not found" in card["error"].lower()
+ assert card.get("type") is None
+
+
+async def test_absent_symbol_name_is_not_reported_as_found(session, repository) -> None:
+ """Degrading to the file card must not claim the symbol resolved."""
+ card = await _card(session, repository, f"{_FILE}::NoSuchMethod")
+ assert card.get("type") != "symbol"
+ assert card.get("docs", {}).get("name") != "NoSuchMethod"
+
+
+# --- degrade to the file card ----------------------------------------------
+
+
+async def test_unresolvable_symbol_degrades_to_its_file_card(session, repository) -> None:
+ """The file half is still an answer, and it carries the real symbol list.
+
+ A bare "Target not found" here is the worst reply available: the caller
+ named a real, indexed file, and the list of ids they should have used is
+ sitting in that file's card.
+ """
+ card = await _card(session, repository, f"{_FILE}::NoSuchMethod")
+ assert "error" not in card
+ assert card["type"] == "file"
+ assert card["resolved_to"] == _FILE
+ assert "NoSuchMethod" in card["note"]
+ # The point of the degrade: the ids the caller needs are in the reply.
+ names = {s["name"] for s in card["docs"]["symbols"]}
+ assert {"AuthService", "login"} <= names
+
+
+async def test_degrade_does_not_fire_for_an_excluded_file(session, repository) -> None:
+ """Exclusion is a boundary rather than a formatting rule; it survives the degrade."""
+ import pathspec
+
+ excluded = pathspec.PathSpec.from_lines("gitwildmatch", ["src/auth/*"])
+ card = await _resolve_one_target(
+ session, repository, f"{_FILE}::NoSuchMethod", None, True, exclude_spec=excluded
+ )
+ assert "error" in card
+ assert "excluded" in card["error"]
+
+
+# --- the graph-node fallback must not type a symbol as a file --------------
+
+
+async def test_symbol_graph_node_is_not_served_as_a_file_card(session, repository) -> None:
+ """A symbol node id matched the file rung and produced a confident lie.
+
+ Call-graph symbol nodes are keyed ``path::Class::method``. The fallback
+ that exists for index-only mode matched that id, typed it ``file``, then
+ looked for symbols whose *file_path* was the whole id, found none, and
+ summarised the method as "empty or non-symbol file". Wrong with
+ confidence is worse than a miss: the reply looks answered.
+
+ The node is not discarded. In index-only mode it is the only record of
+ the symbol, and the callers/callees blocks resolve from it. It is typed as
+ what it is, and its file is the node's file rather than its own id.
+ """
+ ghost = f"{_FILE}::AuthService::ghost_method"
+ session.add(
+ GraphNode(
+ id="gn-ghost",
+ repository_id=repository.id,
+ node_id=ghost,
+ node_type="symbol",
+ name="ghost_method",
+ file_path=_FILE,
+ language="python",
+ )
+ )
+ await session.flush()
+
+ card = await _card(session, repository, ghost)
+ assert "empty or non-symbol file" not in card.get("docs", {}).get("summary", "")
+ assert card["type"] == "symbol"
+ assert card["docs"]["name"] == "ghost_method"
+ # The file is the node's file, not the whole symbol id.
+ assert card["docs"]["file_path"] == _FILE
+ # Fields the node genuinely lacks are absent rather than blank-filled.
+ assert "signature" not in card["docs"]
+
+
+async def test_graph_only_symbol_still_resolves_its_call_graph(session, repository) -> None:
+ """Typing the node correctly must not cost the enrichment it existed for.
+
+ In index-only mode the graph node is the only record of the symbol, and
+ the callers block resolves from it. Dropping the node to avoid the bad
+ file card would have taken this with it.
+ """
+ ghost = f"{_FILE}::AuthService::ghost_method"
+ caller = f"{_FILE}::AuthService::caller"
+ for nid, nm in ((ghost, "ghost_method"), (caller, "caller")):
+ session.add(
+ GraphNode(
+ id=f"gn-{nm}",
+ repository_id=repository.id,
+ node_id=nid,
+ node_type="symbol",
+ name=nm,
+ file_path=_FILE,
+ language="python",
+ )
+ )
+ session.add(
+ GraphEdge(
+ id="ge-ghost",
+ repository_id=repository.id,
+ source_node_id=caller,
+ target_node_id=ghost,
+ edge_type="calls",
+ confidence=0.95,
+ )
+ )
+ await session.flush()
+
+ card = await _resolve_one_target(
+ session, repository, ghost, {"callers"}, True, exclude_spec=None
+ )
+ assert [c["symbol_id"] for c in card["callers"]] == [caller]
diff --git a/tests/unit/server/mcp/test_symbol_callee_depth.py b/tests/unit/server/mcp/test_symbol_callee_depth.py
new file mode 100644
index 000000000..1b25802cd
--- /dev/null
+++ b/tests/unit/server/mcp/test_symbol_callee_depth.py
@@ -0,0 +1,248 @@
+"""get_symbol(depth=N) serves a call chain in one response.
+
+Following a chain by hand costs one round trip per hop, and the graph already
+holds every edge before the first call is made. ``depth`` spends the edges it
+already has instead of the caller's round trips.
+
+The tests below pin the walk itself and, more importantly, its bounds: an
+unbounded graph walk on a hub symbol is a worse failure than the round trips
+it replaces, so every limit is checked from the side that would blow up.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository, WikiSymbol
+from repowise.server.mcp_server import tool_symbol
+from repowise.server.mcp_server.tool_symbol import _MAX_CALLEE_DEPTH, _expand_callees
+
+_FILE = "src/chain.py"
+_SRC = "\n".join(f"def f{i}():\n return f{i + 1}()\n" for i in range(6))
+
+
+async def repository(session, populated_db) -> Repository:
+ return await session.get(Repository, populated_db)
+
+
+async def chain(session, populated_db, tmp_path):
+ """A -> B -> C -> D linear call chain, indexed as symbols, nodes and edges.
+
+ Linear on purpose: the hand-walks this feature replaces are chains, so a
+ chain is what the depth semantics have to be correct about.
+ """
+ rid = populated_db
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "chain.py").write_text(_SRC, encoding="utf-8")
+
+ names = ["f0", "f1", "f2", "f3"]
+ for i, n in enumerate(names):
+ sid = f"{_FILE}::{n}"
+ session.add(
+ WikiSymbol(
+ id=f"cs{i}",
+ repository_id=rid,
+ file_path=_FILE,
+ symbol_id=sid,
+ name=n,
+ qualified_name=f"chain.{n}",
+ kind="function",
+ signature=f"def {n}()",
+ start_line=i * 3 + 1,
+ end_line=i * 3 + 2,
+ language="python",
+ complexity_estimate=1,
+ )
+ )
+ session.add(
+ GraphNode(
+ id=f"cn{i}",
+ repository_id=rid,
+ node_id=sid,
+ node_type="symbol",
+ name=n,
+ file_path=_FILE,
+ language="python",
+ )
+ )
+ for i in range(len(names) - 1):
+ session.add(
+ GraphEdge(
+ id=f"ce{i}",
+ repository_id=rid,
+ source_node_id=f"{_FILE}::{names[i]}",
+ target_node_id=f"{_FILE}::{names[i + 1]}",
+ edge_type="calls",
+ confidence=0.9,
+ )
+ )
+ await session.flush()
+ return tmp_path
+
+
+async def _root(session, rid: str) -> WikiSymbol:
+ from sqlalchemy import select
+
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == rid, WikiSymbol.symbol_id == f"{_FILE}::f0"
+ )
+ )
+ return res.scalar_one()
+
+
+async def test_depth_two_serves_the_direct_callee_with_its_body(
+ session, repository, chain
+) -> None:
+ """The whole point: the next hop arrives with source, not as a name to re-fetch."""
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, 2, None)
+
+ assert [c["symbol_id"] for c in block["callees"]] == [f"{_FILE}::f1"]
+ entry = block["callees"][0]
+ assert entry["depth"] == 1
+ assert "def f1" in entry["source"]
+ assert entry["verified"] is True
+
+
+async def test_depth_three_reaches_two_hops_and_labels_each(
+ session, repository, chain
+) -> None:
+ """Transitive, and each body says how far out it is."""
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, 3, None)
+
+ by_depth = {c["symbol_id"]: c["depth"] for c in block["callees"]}
+ assert by_depth == {f"{_FILE}::f1": 1, f"{_FILE}::f2": 2}
+
+
+async def test_depth_one_does_no_walk_at_all(session, repository, chain) -> None:
+ """Default behaviour is unchanged: no edges are read, nothing is attached."""
+ root = await _root(session, repository.id)
+ assert await _expand_callees(session, repository.id, root, chain, 1, None) is None
+
+
+async def test_a_leaf_symbol_returns_no_block(session, repository, chain) -> None:
+ """No outbound edges must mean no empty block, not an empty list."""
+ from sqlalchemy import select
+
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repository.id,
+ WikiSymbol.symbol_id == f"{_FILE}::f3",
+ )
+ )
+ leaf = res.scalar_one()
+ assert await _expand_callees(session, repository.id, leaf, chain, 3, None) is None
+
+
+# --- the bounds, checked from the side that would blow up ------------------
+
+
+async def test_a_cycle_terminates_and_serves_each_symbol_once(
+ session, repository, chain
+) -> None:
+ """Recursion is normal code. A walk that re-queues a seen node never ends.
+
+ Closing f3 -> f0 makes the chain a cycle; the walk must stop and must not
+ serve the root or any node twice.
+ """
+ session.add(
+ GraphEdge(
+ id="ce-cycle",
+ repository_id=repository.id,
+ source_node_id=f"{_FILE}::f3",
+ target_node_id=f"{_FILE}::f0",
+ edge_type="calls",
+ confidence=0.9,
+ )
+ )
+ await session.flush()
+
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, _MAX_CALLEE_DEPTH, None)
+ ids = [c["symbol_id"] for c in block["callees"]]
+ assert len(ids) == len(set(ids)), "a symbol was served twice"
+ assert f"{_FILE}::f0" not in ids, "the root came back as its own callee"
+
+
+async def test_low_confidence_edges_are_not_followed(session, repository, chain) -> None:
+ """The confidence floor exists because tier-3 resolution invents edges.
+
+ A guessed edge that drags a whole unrelated body into the payload is worse
+ than the missing hop it papers over.
+ """
+ session.add(
+ GraphEdge(
+ id="ce-weak",
+ repository_id=repository.id,
+ source_node_id=f"{_FILE}::f0",
+ target_node_id="src/auth/service.py::AuthService",
+ edge_type="calls",
+ confidence=0.1,
+ )
+ )
+ await session.flush()
+
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, 2, None)
+ assert [c["symbol_id"] for c in block["callees"]] == [f"{_FILE}::f1"]
+
+
+async def test_char_budget_lists_the_dropped_callee_instead_of_hiding_it(
+ session, repository, chain, monkeypatch
+) -> None:
+ """Silent truncation reads as "this is the whole chain". It must not.
+
+ Squeezed to a budget that fits nothing, the callee still appears, with the
+ exact range read that fetches it.
+ """
+ monkeypatch.setattr(tool_symbol, "_CALLEE_CHAR_BUDGET", 1)
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, 2, None)
+
+ assert block["callees"] == []
+ dropped = block["not_rendered"][0]
+ assert dropped["symbol_id"] == f"{_FILE}::f1"
+ assert dropped["fetch_with"] == f"{_FILE}:4-5"
+ assert "not_rendered" in block["note"]
+
+
+# --- the wiring, through the tool itself -----------------------------------
+
+
+async def test_get_symbol_attaches_callee_bodies_and_clamps_depth(
+ session, setup_mcp, chain, monkeypatch
+) -> None:
+ """The parameter has to survive the tool boundary, not just the helper.
+
+ Also pins the clamp: an out-of-range depth is a caller reaching for more
+ of the chain, so it is bounded rather than rejected.
+ """
+ import repowise.server.mcp_server as mcp_mod
+ from repowise.server.mcp_server.tool_symbol import get_symbol
+
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(chain))
+ await session.commit()
+
+ plain = await get_symbol(symbol_id=f"{_FILE}::f0")
+ assert "callee_bodies" not in plain, "depth defaults to no walk"
+
+ walked = await get_symbol(symbol_id=f"{_FILE}::f0", depth=99)
+ block = walked["callee_bodies"]
+ assert block["depth"] == _MAX_CALLEE_DEPTH
+ assert {c["name"] for c in block["callees"]} == {"f1", "f2"}
+ # The root's own body is still the primary payload.
+ assert "def f0" in walked["source"]
+
+
+async def test_excluded_callees_are_dropped(session, repository, chain) -> None:
+ """Exclusion is a boundary; a graph walk must not route around it."""
+ import pathspec
+
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["src/chain.py"])
+ root = await _root(session, repository.id)
+ block = await _expand_callees(session, repository.id, root, chain, 3, spec)
+ assert block is None