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.

refactor(mcp): split tool_symbol into a package of read stages (#4052)

Raghav Chamadiya7fa698122cd6
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
deleted file mode 100644
index 8be985ac1..000000000
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ /dev/null
@@ -1,1472 +0,0 @@
-"""MCP Tool: get_symbol — byte-precise source retrieval for a single symbol.
-
-This is the structural counterpart to get_context. Where get_context returns
-file-level narrative (summary, symbol list, importers), get_symbol returns
-the actual source bytes of one named symbol — function body, class body, or
-method — by slicing the on-disk source file using the line range stored on
-the WikiSymbol row at index time.
-
-Why a separate tool instead of "include source" on get_context?
- * Granularity: a single function is ~30 lines vs a 300-line file. Cuts the
- cached prompt prefix by ~10x when the agent only needs one symbol.
- * Predictability: response size is bounded by the symbol size, never the
- file size — no surprise 50 KB payloads.
- * Verified bounds: the persisted line range is checked against the live
- file before serving (name-on-definition-line gate); on mismatch the
- file is re-parsed once, the bounds corrected and healed in the DB. A
- ``verified: true`` response never needs a follow-up Read.
-
-The tool is intentionally additive — get_context remains the right call for
-"explain this file" or "what's the relationship between A and B" questions.
-get_symbol is for "show me the body of this function".
-
-Resolution strategy (in order):
- 1. Exact match on WikiSymbol.symbol_id (the canonical "{path}::{name}" key)
- 2. Exact match on (file_path, qualified_name) — supports class.method form
- 3. Exact match on (file_path, name) — supports unqualified names
- 4. Suffix match — a bare filename or partial path ("answer.py::get_answer")
- resolves against any file whose path ends with that segment, on the leaf
- name; mirrors get_context's basename ladder. A total miss returns
- ``suggestions`` (real path-qualified ids) instead of a bare "not found".
-
-The tool also resolves **omission refs**: a ``symbol_id`` of the form
-``"repowise#<12-hex>"`` (from a ``[repowise#<ref>: ...]`` truncation marker)
-retrieves the omitted content from the durable omission store instead of the
-symbol index. The two id shapes are syntactically unambiguous — a real
-symbol_id always contains a file path — so dispatch is trivial and the
-symbol contract is untouched.
-
-Returns a flat dict (not wrapped in `targets`) so the agent can pipe the
-`source` field straight to its scratch buffer.
-"""
-
-from __future__ import annotations
-
-import functools
-import json
-import re
-import sqlite3
-import time
-from collections.abc import Sequence
-from datetime import UTC, datetime
-from pathlib import Path
-from typing import Any, NamedTuple
-
-from sqlalchemy import select
-
-from repowise.core.persistence.database import get_session
-from repowise.core.persistence.models import WikiSymbol
-from repowise.core.registry import mcp_tool_registry as mcp
-from repowise.server.mcp_server._budget import register_post_shed
-from repowise.server.mcp_server._budget.contracts import DEFAULT_RESPONSE_CHARS
-from repowise.server.mcp_server._helpers import (
- _get_exclude_spec,
- _get_repo,
- _is_workspace_mode,
- _resolve_repo_context,
- _unsupported_repo_all,
- clean_signature,
- 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 completeness_line as _completeness_line
-from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
-from repowise.server.mcp_server._references import (
- omission_reference,
- path_identity,
- source_reference,
- symbol_identity,
-)
-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,
- parse_live_symbols,
-)
-from repowise.server.mcp_server._workspace_routing import (
- hint_misses,
- needs_routing,
- other_repo_roots,
- route_targets,
-)
-
-_log = __import__("logging").getLogger("repowise.mcp.symbol")
-
-# Safety cap so a misconfigured WikiSymbol row pointing at a giant file
-# can never blow up the agent's context window. Set to ~18 KB of source:
-# on a real index 99.93% of symbols are <600 lines, so a single get_symbol
-# serves the WHOLE body in one call for all but a handful of monster
-# functions — round-trip count, not payload size, is what dominates agent
-# token cost (S1 dogfood). The rare overflow gets a clean `continuation`
-# token rather than a guessed range read.
-_MAX_SOURCE_LINES = 600
-
-# A container whose served body would exceed this is outlined instead: its
-# header plus each member's signature, lines and id. Half the default reply
-# budget, so smaller classes keep the one-call whole body, while a class big
-# enough to crowd out the rest of the reply is usually wanted for its shape.
-_OUTLINE_MIN_CHARS = DEFAULT_RESPONSE_CHARS // 2
-_CONTAINER_KINDS = frozenset({"class", "interface", "struct", "enum", "trait", "impl", "module"})
-# Header lines (decorators, declaration, docstring head) served above members.
-_OUTLINE_HEADER_LINES = 12
-_OUTLINE_SUMMARY_CHARS = 160
-# Serialized chars of member rows listed; the rest are counted in members_total.
-_OUTLINE_MEMBER_CHARS = DEFAULT_RESPONSE_CHARS // 2
-
-# Range-read dispatch: "path/to/file.py:140-180". A single colon followed by
-# a numeric range never collides with "{path}::{name}" (double colon) or an
-# omission ref. The escape hatch for everything not indexed as a symbol —
-# imports, module docstrings, decorators between symbols — without falling
-# back to a whole-file Read.
-_RANGE_ID_RE = re.compile(r"^(?P<path>.+?):(?P<start>\d+)-(?P<end>\d+)$")
-
-# Range reads are bounded tighter than symbol reads: the caller names exact
-# lines, so a large range is a deliberate choice to cap.
-_MAX_RANGE_LINES = 200
-
-# Dead-end recovery: max grep matches returned when a symbol lookup misses
-# but the file exists on disk.
-_MAX_FALLBACK_MATCHES = 8
-
-# A matched line that declares the name rather than using it: a definition
-# keyword at line start, after decorators and modifiers. Keyword-based, so a
-# definition without one (``const f = () =>``) reads as a plain match.
-_DEF_KEYWORDS = r"(?:def|class|function\*?|func|fn|struct|interface|enum|trait|type|module|sub)"
-_DEF_MODIFIERS = (
- r"(?:(?:export|default|pub(?:\([^)]*\))?|public|private|protected|internal|static"
- r"|abstract|final|override|virtual|async|unsafe|extern|inline|open|sealed|partial|data)\s+)*"
-)
-_COMMENT_PREFIXES = ("#", "//", "/*", "*", "--", ";")
-
-# Rows read when matching a name across files. A scan that fills it is not
-# exhaustive, so its single survivor is never taken as the only match.
-_NAME_SCAN_CAP = 20
-
-# When a lookup is ambiguous (overloads, re-exports, conditional defs) every
-# candidate body is served in ONE response — a silently-picked wrong candidate
-# sends the agent into a read-spiral that costs far more than the extra bytes.
-# This caps the total candidate-source chars; the first candidate always
-# renders, the rest render while budget remains and are otherwise listed with
-# an exact range read that fetches them.
-_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. Enforced across the
-# whole frontier, not per node: passing it only to the per-node edge query let a
-# hop of N nodes yield up to 12xN callees, and on a 12-node frontier whose nodes
-# call 14 each the walk produced **144 rows against this documented cap of 12**.
-# The constant's name meant a hop; the code meant a node.
-_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
-
-
-class _CalleeHop(NamedTuple):
- """One hop of the walk: its true graph distance and the rows it produced.
-
- ``over_cap`` counts rows the per-hop fan-out cap dropped. They are reported
- as a number rather than as entries: listing them individually is the payload
- the cap exists to prevent, and saying nothing would make a silent cut out of
- a bound this module otherwise always makes recoverable. It is a floor over
- the indexed graph, not a total — the per-node edge query carries its own
- limit, so callees it never returned are not counted here either.
- """
-
- number: int
- rows: list[WikiSymbol]
- over_cap: int
-
-
-class _CalleeBody(NamedTuple):
- """One callee's rendered body, sliced once and costed by its own length.
-
- ``declared_*`` are the bounds the verified row claims; ``start``/``end`` are
- what the line cap actually served, so ``end < declared_end`` is exactly the
- truncation case.
- """
-
- source: str
- start: int
- end: int
- declared_start: int
- declared_end: int
- verified: bool
-
-
-def _slice_callee_body(row: WikiSymbol, text: str) -> _CalleeBody:
- """Slice *row* out of *text* under the callee line cap.
-
- 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
- )
- return _CalleeBody(
- source=_number_lines(source, start),
- start=start,
- end=end,
- declared_start=check.start_line,
- declared_end=check.end_line,
- verified=check.verified,
- )
-
-
-async def _unseen_callees_of(
- session,
- repo_id: str,
- frontier: list[str],
- seen: set[str],
-) -> tuple[list[str], dict[str, float]]:
- """Call targets of *frontier* not already in *seen*, with their confidence.
-
- Mutates *seen*, which is what keeps a diamond from being walked twice.
- Edges below the confidence floor are dropped here: tier-3 resolution
- invents edges, and a guessed one drags a whole unrelated body into the
- payload.
- """
- 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,
- )
-
- next_ids: list[str] = []
- confidence_of: dict[str, float] = {}
- 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 or e.target_node_id in seen:
- continue
- seen.add(e.target_node_id)
- next_ids.append(e.target_node_id)
- confidence_of[e.target_node_id] = e.confidence or 0
- return next_ids, confidence_of
-
-
-async def _discover_callee_hops(
- session,
- repo_id: str,
- root_row: WikiSymbol,
- depth: int,
- exclude_spec: Any,
-) -> list[_CalleeHop]:
- """Walk the call graph and return the rows of each hop, no bodies read.
-
- Discovery is separate from rendering so the renderer knows, before it
- spends the first character, how many hops actually produced rows. Reserving
- a slice of the budget for a hop that turns out to be empty costs a body
- that would otherwise have been served.
-
- 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 reached at most once, at the
- shallowest depth that reaches it, which keeps a diamond in the call graph
- from being serialised twice. A symbol past the per-hop fan-out cap is not
- re-offered at a deeper hop: it would then be labelled with a distance that
- is not its own. It is counted in ``over_cap`` instead.
- """
- seen: set[str] = {root_row.symbol_id}
- frontier = [root_row.symbol_id]
- hops: list[_CalleeHop] = []
-
- for hop_number in range(1, depth):
- if not frontier:
- break
- next_ids, confidence_of = await _unseen_callees_of(session, repo_id, frontier, seen)
- 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)]
- # The cap the constant documents: one hop, not one frontier node. It is
- # applied *after* the row lookup and the exclusion filter, so a dangling
- # edge or an excluded path cannot spend a slot — cutting the ids first
- # let a hop whose twelve most confident targets all sat under an
- # excluded prefix come back empty while valid callees waited behind it.
- # The cut itself is ranked by edge confidence, which is the contract
- # ``get_graph_edges_for_node`` already documents for its own limit: an
- # unranked cut is deterministic and still the wrong rows.
- rows.sort(key=lambda r: (-confidence_of.get(r.symbol_id or "", 0.0), r.symbol_id or ""))
- over_cap = max(len(rows) - _MAX_CALLEES_PER_HOP, 0)
- rows = rows[:_MAX_CALLEES_PER_HOP]
- # 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 ""))
- if rows:
- # The hop number is carried, not inferred from the position in this
- # list: a hop whose rows were all excluded or all dangling would
- # otherwise renumber every hop behind it, and a grandchild would be
- # served claiming to be a direct callee.
- hops.append(_CalleeHop(number=hop_number, rows=rows, over_cap=over_cap))
- frontier = next_ids
-
- return hops
-
-
-def _prepare_callee_entries(
- hops: list[_CalleeHop], repo_root: Path
-) -> list[tuple[dict[str, Any], str, _CalleeBody | None]]:
- """One ordered record per discovered row: ``(entry, file_path, body)``.
-
- ``body`` is None when the file could not be read. The order is fixed here,
- so the later refill pass cannot reshuffle the payload, and each body is
- sliced exactly once, so what a body costs and what is emitted for it can
- never disagree.
- """
- text_cache: dict[str, str | None] = {}
- prepared: list[tuple[dict[str, Any], str, _CalleeBody | None]] = []
- for hop in hops:
- for row in hop.rows:
- entry: dict[str, Any] = {
- "symbol_id": symbol_identity(row.symbol_id),
- "name": row.name,
- "file": row.file_path,
- "kind": row.kind,
- "signature": clean_signature(row.signature),
- "depth": hop.number,
- }
- 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]
- body = None if text is None else _slice_callee_body(row, text)
- prepared.append((entry, row.file_path, body))
- return prepared
-
-
-async def _expand_callees(
- session,
- repo_id: str,
- root_row: WikiSymbol,
- repo_root: Path,
- depth: int,
- exclude_spec: Any,
- repository: str = "default",
-) -> dict[str, Any] | None:
- """Breadth-first walk of the call graph from *root_row*, bodies included.
-
- Bodies are served against a per-hop share of the character budget rather
- than in loop order. Spending in loop order meant every hop-1 body was
- served before hop 2 was reached, so a handful of large direct callees
- exhausted the budget and the deeper hops the caller asked for arrived as
- references. Measured on a 20x3 hub: 10 hop-1 bodies and **zero** at hop 2;
- with a reserved share, 5 and 5.
-
- The reservation is taken only across hops that discovery found rows for,
- and whatever the reserve leaves unspent is refilled to the bodies it
- deferred, in hop order — so a direct callee is first in line for a share
- the deeper hops did not use. Both matter: a naive reserve cost a two-leaf
- root at depth 3 one of its two bodies in exchange for a hop 2 that was
- empty, and a reserve that only bound the shallow hops let hop 2 drain the
- budget a deferred hop-1 body was waiting on.
-
- Returns None when the root has no outbound call edges, so the caller adds
- no empty block to an ordinary response.
- """
- hops = await _discover_callee_hops(session, repo_id, root_row, depth, exclude_spec)
- if not hops:
- return None
-
- remaining = _CALLEE_CHAR_BUDGET
- reserve_per_hop = _CALLEE_CHAR_BUDGET // len(hops)
- prepared = _prepare_callee_entries(hops, repo_root)
-
- def _render(entry: dict[str, Any], file_path: str, body: _CalleeBody) -> None:
- entry.update(
- {
- "start_line": body.start,
- "end_line": body.end,
- "source": body.source,
- "verified": body.verified,
- }
- )
- if body.end < body.declared_end:
- entry["truncated"] = True
- continuation_reference = source_reference(
- repository,
- file_path,
- lines=[body.end + 1, body.declared_end],
- verification_basis="live",
- source_kind="source",
- )
- entry["continuation"] = continuation_reference["id"]
- entry["continuation_reference"] = continuation_reference
-
- # Pass 1: every hop spends its own share and no more — including the last,
- # which is why this is a cap and not a floor. Subtracting only the shares
- # still owed to *deeper* hops let unspent budget flow forward: a hop-1 body
- # one character over its share was deferred, the deeper hops then drained
- # everything behind it, and the direct callee — the most relevant body in
- # the response — came back as a reference. That is worse than the code this
- # replaces. Leftovers are redistributed by pass 2 instead, in hop order.
- for hop in hops:
- spendable = min(reserve_per_hop, remaining)
- for entry, file_path, body in prepared:
- if entry["depth"] != hop.number or body is None or "source" in entry:
- continue
- if len(body.source) > spendable:
- continue
- _render(entry, file_path, body)
- remaining -= len(body.source)
- spendable -= len(body.source)
-
- # Pass 2: a reserve nobody claimed goes back to whatever it deferred, in
- # hop order, so an empty deeper hop costs the caller nothing.
- for entry, file_path, body in prepared:
- if body is None or "source" in entry or len(body.source) > remaining:
- continue
- _render(entry, file_path, body)
- remaining -= len(body.source)
-
- entries: list[dict[str, Any]] = []
- omitted: list[dict[str, Any]] = []
- for entry, file_path, body in prepared:
- if "source" in entry:
- entries.append(entry)
- elif body is None:
- entry["note"] = "source file could not be read"
- omitted.append(entry)
- else:
- # Out of budget: name the read that fetches it rather than
- # dropping the symbol silently.
- fetch_reference = source_reference(
- repository,
- file_path,
- lines=[body.declared_start, body.declared_end],
- verification_basis="live",
- source_kind="source",
- )
- entry["fetch_with"] = fetch_reference["id"]
- entry["fetch_reference"] = fetch_reference
- omitted.append(entry)
-
- block: dict[str, Any] = {"depth": depth, "callees": entries}
- fan_out_capped = [
- {"depth": hop.number, "omitted": hop.over_cap} for hop in hops if hop.over_cap
- ]
- if fan_out_capped:
- block["fan_out_capped"] = fan_out_capped
- 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 _extract_omission_ref(symbol_id: str) -> str | None:
- """Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""
- from repowise.server.mcp_server._references import omission_reference
-
- canonical = omission_reference(symbol_id)
- return canonical.removeprefix("repowise#") if canonical else None
-
-
-def _resolve_omission_ref(
- symbol_id: str,
- ref: str,
- query: str | None,
- repo_root: Any,
- t0: float,
- other_roots: Sequence[tuple[str, Path]] = (),
-) -> dict:
- """Look *ref* up in the omission store(s) and shape a tool response.
-
- Checks the repo-local store first, then the stores of *other_roots* (the
- other workspace repos, whose responses write their own), then the
- user-level fallback — the same order as ``repowise expand``. Stores are
- only opened when the DB file already exists (opening would otherwise
- create an empty one). A ref is a content hash, so the first store holding
- it has the content.
- """
- from repowise.core.distill.store import OmissionStore, default_store_path
-
- canonical_ref = f"repowise#{ref}"
- candidates: list[tuple[str | None, Path]] = []
- if repo_root:
- candidates.append((None, default_store_path(Path(str(repo_root)))))
- for alias, root in other_roots:
- candidates.append((alias, default_store_path(root)))
- home_store = default_store_path(Path.home())
- if home_store not in {path for _alias, path in candidates}:
- candidates.append((None, home_store))
-
- record: dict | None = None
- found_in: str | None = None
- for alias, db_path in candidates:
- try:
- if not db_path.exists():
- continue
- store = OmissionStore(db_path)
- try:
- record = store.get_record(ref, query=query)
- finally:
- store.close()
- except (OSError, sqlite3.Error):
- # An inaccessible fallback store is equivalent to a missing ref.
- # Recovery must never make get_symbol itself fail.
- continue
- if record is not None:
- found_in = alias
- break
-
- if record is None:
- return {
- "symbol_id": symbol_id,
- "ref": canonical_ref,
- "error": (
- f"No stored content for omission ref {ref!r} — it may have "
- "expired (7-day TTL), been pruned, or been produced in a "
- "different repo. Re-run the original call for fresh content."
- ),
- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
- }
-
- created = record.get("created_at")
- response: dict[str, Any] = {
- **({"repo": found_in} if found_in else {}),
- "symbol_id": symbol_id,
- "ref": canonical_ref,
- "kind": "omission",
- "source": record.get("source"),
- "original_tokens": record.get("original_tokens"),
- "content": record.get("content"),
- "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
- }
- if isinstance(created, (int, float)):
- response["created_at"] = datetime.fromtimestamp(created, tz=UTC).isoformat()
- if query is not None:
- response["query"] = query
- if not record.get("content"):
- response["note"] = "No lines matched the query; omit query for the full content."
- return response
-
-
-async def _resolve_range_read(
- symbol_id: str, path: str, start: int, end: int, context_lines: int, ctx: Any, t0: float
-) -> dict:
- """Serve a live, bounded line-range read: "path/to/file.py:140-180".
-
- Always ``verified: true`` — the bytes come straight from the live file
- at the requested lines. Bounded to _MAX_RANGE_LINES; the full-file token
- count is declared as the counterfactual (the Read this call replaced).
- """
- repository = None
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
-
- def _err(msg: str) -> dict:
- return {
- "symbol_id": symbol_id,
- "error": msg,
- "_meta": _build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000, repository=repository
- ),
- }
-
- # Before the exclusion spec: it is built from the repo path.
- if not ctx.path:
- return _err("MCP server has no repo path configured")
- if is_excluded(path, _get_exclude_spec(ctx.path)):
- return _err(f"'{path}' is excluded from indexing.")
-
- text = _read_file_text(Path(str(ctx.path)), path)
- if text is None:
- return _err(f"File could not be read: {path!r}")
-
- from repowise.core.distill.budget import estimate_tokens
-
- full_tokens = estimate_tokens(text)
-
- if end < start:
- start, end = end, start
- requested_end = end
- requested_truncated = (end - start + 1) > _MAX_RANGE_LINES
- if requested_truncated:
- end = start + _MAX_RANGE_LINES - 1
-
- # Cap the served span at _MAX_RANGE_LINES *including* context expansion —
- # the docstring promises ≤200 lines, so context_lines must not push past
- # it. Truncated reflects either an oversized request or a context-clipped
- # span.
- source, s, e, total = _slice_text(text, start, end, context_lines, max_lines=_MAX_RANGE_LINES)
- range_truncated = requested_truncated or (e - s + 1) >= _MAX_RANGE_LINES
-
- response = {
- "symbol_id": symbol_id,
- "file": path,
- "kind": "range",
- "start_line": s,
- "end_line": e,
- "total_lines": total,
- "source": _number_lines(source, s),
- "truncated": range_truncated,
- "verified": True,
- "_meta": _build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000,
- repository=repository,
- # A range read serves live bytes; index drift elsewhere is noise.
- targets=[path],
- ),
- }
- if s == 1 and e == total and not range_truncated:
- # Only a range that covers the file end to end is a whole unit; any
- # other slice leaves lines the caller still has to go and read.
- response["_meta"]["complete"] = _completeness_line(files=1)
- remainder_end = min(requested_end, total)
- if range_truncated and e < remainder_end:
- # Same clean-continuation contract as a truncated symbol read: name the
- # exact next range instead of leaving the agent to guess it.
- continuation_reference = source_reference(
- ctx.alias,
- path,
- lines=[e + 1, remainder_end],
- verification_basis="live",
- source_kind="source",
- )
- response["continuation"] = continuation_reference["id"]
- response["continuation_reference"] = continuation_reference
- response["note"] = (
- f"Range capped at {_MAX_RANGE_LINES} lines; served {s}-{e}. "
- f"Continue in one call: get_symbol({response['continuation']!r})."
- )
- from repowise.server.mcp_server._savings import declare_replaced
-
- declare_replaced(response, full_tokens)
- return response
-
-
-def _live_grep_fallback(repo_root: Path, file_path: str, name: str) -> list[dict]:
- """Find ``name`` in the live file when the symbol index misses.
-
- Turns a dead-end call (pure cost) into an answer: constants, imports,
- aliases, and decorators live between indexed symbols, and the line that
- defines them is usually all the agent needs. ±2 lines of context per
- match, capped at _MAX_FALLBACK_MATCHES.
- """
- text = _read_file_text(repo_root, file_path)
- if text is None:
- return []
- bare = _bare_name(name)
- if not bare:
- return []
- defines = re.compile(
- rf"^\s*(?:@\S+\s+)*{_DEF_MODIFIERS}{_DEF_KEYWORDS}\s+(?:\([^)]*\)\s*)?{re.escape(bare)}\b"
- )
- lines = text.splitlines()
- matches: list[dict] = []
- for i, line in enumerate(lines, 1):
- if bare in line:
- lo, hi = max(1, i - 2), min(len(lines), i + 2)
- match = {"line": i, "context": _number_lines("\n".join(lines[lo - 1 : hi]), lo)}
- if not line.lstrip().startswith(_COMMENT_PREFIXES) and defines.match(line):
- match["defines"] = True
- matches.append(match)
- if len(matches) >= _MAX_FALLBACK_MATCHES:
- break
- return matches
-
-
-# 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 _symbols_named(
- session, repo_id: str, symbol_id: str, exclude_spec
-) -> tuple[list[str], bool]:
- """Non-excluded ids of symbols carrying the name in *symbol_id*.
-
- The second value says whether the scan saw every row with that name, so a
- caller can tell "exactly one" from "one survivor of a capped scan".
- """
- qualified = "::" in symbol_id
- # A bare name is matched whole: it has no path half to strip.
- name = _parse_symbol_id(symbol_id)[1] if qualified else symbol_id.strip()
- if not name:
- return [], True
- bare = _bare_name(name) if qualified else name
- res = await session.execute(
- select(WikiSymbol.symbol_id, WikiSymbol.file_path)
- .where(WikiSymbol.repository_id == repo_id, WikiSymbol.name == bare)
- .order_by(WikiSymbol.symbol_id)
- .limit(_NAME_SCAN_CAP)
- )
- rows = res.all()
- ids = [sid for sid, fpath in rows if sid and not is_excluded(fpath, exclude_spec)]
- return list(dict.fromkeys(ids)), len(rows) < _NAME_SCAN_CAP
-
-
-async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spec) -> list[str]:
- """Concrete symbol_ids to retry when a lookup misses entirely.
-
- The caller usually had the right leaf name but a wrong or partial path.
- Match that name across every file and hand back real ids (path-qualified)
- the agent can pass straight back to get_symbol — a bare "not found" would
- otherwise send it to get_context or a whole-file Read.
- """
- ids, _ = await _symbols_named(session, repo_id, symbol_id, exclude_spec)
- return ids[:5]
-
-
-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."""
- 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(
- text: str,
- start_line: int,
- end_line: int,
- context_lines: int,
- max_lines: int = _MAX_SOURCE_LINES,
-) -> tuple[str, int, int, int]:
- """Slice ``text`` to (source, actual_start, actual_end, total_lines).
-
- Lines are 1-indexed inclusive to match WikiSymbol storage; the range is
- expanded by ``context_lines`` on both sides and capped at ``max_lines``
- (truncating from the tail — the head carries the signature, which is what
- the agent needs to ground itself). The cap is applied AFTER context
- expansion so the returned span never exceeds it.
- """
- lines = text.splitlines()
- total = len(lines)
-
- s = max(1, min(start_line, total))
- e = max(s, min(end_line, total))
- if context_lines > 0:
- s = max(1, s - context_lines)
- e = min(total, e + context_lines)
-
- if (e - s + 1) > max_lines:
- e = s + max_lines - 1
-
- return "\n".join(lines[s - 1 : e]), s, e, total
-
-
-def _number_lines(source: str, start_line: int) -> str:
- """Prefix each line with its 1-based file line number, Read-style.
-
- Byte-parity with the agent's own Read tool output (``cat -n`` format:
- right-aligned number, tab, line). Source served in the exact shape of an
- already-performed Read is treated as one — the agent edits from it
- instead of re-Reading the file to "see the real format".
- """
- return "\n".join(f"{n:>6}\t{line}" for n, line in enumerate(source.splitlines(), start_line))
-
-
-async def _container_outline(
- session_factory: Any, repo_id: str, row: WikiSymbol, text: str, start: int, end: int
-) -> tuple[list[dict[str, Any]], int, int] | None:
- """Direct members of the container *row* spanning ``start``-``end``, as outline rows.
-
- Returns the listed rows (capped at ``_OUTLINE_MEMBER_CHARS``), the line the
- first member starts on and the member total, or None when the index holds
- no members to outline. Each member is verified against the live file,
- parsing it at most once for the whole set.
-
- Members are matched by parent name inside the container's own lines, so
- Rust impl blocks and Go receiver methods declared outside a struct do not
- outline it.
- """
- async with get_session(session_factory) as session:
- res = await session.execute(
- select(WikiSymbol).where(
- WikiSymbol.repository_id == repo_id,
- WikiSymbol.file_path == row.file_path,
- WikiSymbol.parent_name == row.name,
- WikiSymbol.id != row.id,
- )
- )
- rows = list(res.scalars().all())
- _parsed = functools.cache(lambda: parse_live_symbols(row, text))
- members: list[dict[str, Any]] = []
- for member in rows:
- check = check_symbol_bounds(member, text, _parsed)
- # A same-named container elsewhere in the file shares the parent name;
- # an unverified member is judged by its indexed range instead.
- if check.approximate:
- if not start <= member.start_line <= member.end_line <= end:
- continue
- elif not start <= check.start_line <= end:
- continue
- entry: dict[str, Any] = {
- "symbol_id": symbol_identity(member.symbol_id),
- "kind": member.kind,
- "signature": clean_signature(member.signature),
- "start_line": check.start_line,
- "end_line": check.end_line,
- }
- summary = (member.docstring or "").strip().splitlines()
- if summary:
- entry["summary"] = summary[0][:_OUTLINE_SUMMARY_CHARS]
- if check.approximate:
- entry["bounds"] = "approximate"
- members.append(entry)
- if not members:
- return None
- members.sort(key=lambda m: m["start_line"])
- # Overloads share one id, and get_symbol on it already serves every one.
- unique: dict[str, dict[str, Any]] = {}
- for entry in members:
- unique.setdefault(entry["symbol_id"], entry)
- members = list(unique.values())
- first = min((m["start_line"] for m in members if "bounds" not in m), default=end + 1)
- listed: list[dict[str, Any]] = []
- remaining = _OUTLINE_MEMBER_CHARS
- for entry in members:
- remaining -= len(json.dumps(entry)) + 2
- if remaining < 0:
- break
- listed.append(entry)
- return listed, first, len(members)
-
-
-async def _render_ambiguous(
- rows: list[WikiSymbol],
- symbol_id: str,
- ctx: Any,
- repository: Any,
- t0: float,
- context_lines: int,
-) -> dict:
- """Serve EVERY candidate body for an ambiguous symbol id in one response.
-
- A deterministic-but-wrong pick reads as authoritative and sends the agent
- editing the wrong overload; returning all candidates costs bytes once and
- removes the guess. The first candidate always renders; the rest render
- while the char budget lasts and are otherwise listed with the exact range
- read that fetches them.
- """
- repo_root = Path(str(ctx.path))
- text_cache: dict[str, str | None] = {}
- candidates: list[dict] = []
- not_rendered: list[dict] = []
- remaining = _AMBIGUITY_CHAR_BUDGET
- whole_bodies = 0
-
- for i, row in enumerate(rows):
- 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]
-
- entry: dict[str, Any] = {
- "symbol_id": symbol_identity(row.symbol_id),
- "file": row.file_path,
- "name": row.name,
- "kind": row.kind,
- "qualified_name": row.qualified_name,
- "signature": row.signature,
- }
- if text is None:
- entry["note"] = "source file could not be read"
- not_rendered.append(entry)
- continue
-
- check = check_symbol_bounds(row, text)
- if check.corrected:
- await heal_symbol_row(ctx.session_factory, row, check.start_line, check.end_line)
- source, start, end, _total = _slice_text(
- text, check.start_line, check.end_line, context_lines
- )
- entry.update({"start_line": start, "end_line": end, "verified": check.verified})
-
- numbered = _number_lines(source, start)
- if i > 0 and len(numbered) > remaining:
- fetch_reference = source_reference(
- ctx.alias,
- row.file_path,
- lines=[start, end],
- verification_basis="live",
- source_kind="source",
- )
- entry["fetch_with"] = fetch_reference["id"]
- entry["fetch_reference"] = fetch_reference
- not_rendered.append(entry)
- continue
- remaining -= len(numbered)
- entry["source"] = numbered
- candidates.append(entry)
- # A candidate is whole only when the served span reaches both ends of
- # the verified bounds; a budget-clipped or relocated one does not count.
- if check.verified and start <= check.start_line and end >= check.end_line:
- whole_bodies += 1
-
- response: dict[str, Any] = {
- "symbol_id": symbol_id,
- "ambiguous": True,
- "match_count": len(rows),
- "candidates": candidates,
- "note": (
- f"{len(rows)} symbols match this id (overloads, re-exports, or "
- "conditional definitions). All candidate bodies are included — "
- "none was silently chosen; pick by signature and line range."
- ),
- "_meta": _build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000,
- repository=repository,
- targets=sorted({r.file_path for r in rows}),
- ),
- }
- if whole_bodies:
- response["_meta"]["complete"] = _completeness_line(bodies=whole_bodies)
- if not_rendered:
- response["not_rendered"] = not_rendered
- response["note"] += (
- " Candidates over the response budget are listed in not_rendered —"
- " fetch one via get_symbol with its fetch_with range."
- )
-
- from repowise.core.distill.budget import estimate_tokens
- from repowise.server.mcp_server._savings import declare_replaced
-
- full_tokens = sum(estimate_tokens(t) for t in text_cache.values() if t)
- if full_tokens:
- declare_replaced(response, full_tokens)
- return response
-
-
-def _correct_ambiguity_note(result: dict[str, Any], _collector: Any) -> None:
- """Stop promising every candidate body once the budget has cut some.
-
- The ambiguous shape exists so a wrong pick is never made silently, and says
- so in ``note``. A shed that leaves the note standing makes exactly the
- claim the shape was built to avoid.
- """
- if not result.get("ambiguous"):
- return
- emitted = result.get("candidates_emitted")
- if emitted is None or emitted >= (result.get("match_count") or 0):
- return
- result["note"] = (
- f"{result.get('match_count')} symbols match this id (overloads, "
- f"re-exports, or conditional definitions). {emitted} candidate bodies "
- "fit this response; the rest are recoverable from the omission ref, or "
- "fetch one directly with its file range."
- )
-
-
-register_post_shed("get_symbol", _correct_ambiguity_note)
-
-
-def _elapsed_ms(t0: float) -> float:
- return (time.perf_counter() - t0) * 1000
-
-
-def _reference_arguments(
- reference: dict[str, Any] | None,
- symbol_id: str | None,
- id: str | None,
- repo: str | None,
-) -> tuple[str | None, str | None]:
- """``symbol_id`` and ``repo`` filled from a structured source reference."""
- if not reference:
- return symbol_id, repo
- if not symbol_id and not id and isinstance(reference.get("id"), str):
- symbol_id = reference["id"]
- if repo is None and _is_workspace_mode() and isinstance(reference.get("repository"), str):
- repo = reference["repository"]
- return symbol_id, repo
-
-
-def _requested_id(
- symbol_id: str | None, id: str | None, query: str | None
-) -> tuple[str | None, str | None]:
- """The id asked for, from ``symbol_id``, its ``id`` alias, or a lone ``query``."""
- # Agents call this tool as ``get_symbol(id)``; ``symbol_id`` wins when both are given.
- if not symbol_id and id:
- symbol_id = id
- elif not symbol_id and query and query.strip():
- # A lone ``query`` is a guessed id: the line filter needs an id to apply to.
- symbol_id, query = query, None
- return symbol_id, query
-
-
-async def _routed_read(
- symbol_id: str, context_lines: int, query: str | None, depth: int
-) -> dict | None:
- """The read served by the repo that owns *symbol_id*, or None to serve it here."""
- routes = await route_targets([symbol_id.strip()])
- if not needs_routing(routes):
- return None
- route = routes[0]
- if route.repo is None:
- return {"symbol_id": symbol_id, **route.card(), "_meta": _build_meta()}
- routed = await get_symbol(
- route.local, context_lines=context_lines, repo=route.repo, query=query, depth=depth
- )
- if route.routed:
- routed = {"repo": route.repo, **routed}
- hint_misses(routed, routes)
- return routed
-
-
-async def _range_id_read(symbol_id: str, context_lines: int, ctx: Any, t0: float) -> dict | None:
- """A live range read for a ``path:start-end`` id, else None."""
- range_match = _RANGE_ID_RE.match(symbol_id.strip())
- if not range_match or "::" in symbol_id:
- return None
- normalized_path = path_identity(range_match.group("path"))
- range_start = int(range_match.group("start"))
- range_end = int(range_match.group("end"))
- if range_end < range_start:
- range_start, range_end = range_end, range_start
- normalized_id = f"{normalized_path}:{range_start}-{range_end}"
- return await _resolve_range_read(
- normalized_id,
- normalized_path,
- range_start,
- range_end,
- max(0, min(50, context_lines)),
- ctx,
- t0,
- )
-
-
-async def _rows_in_scope(
- ctx: Any, repository: Any, symbol_id: str, rows: list[Any], exclude_spec: Any
-) -> list[Any]:
- """*rows* outside the exclusion spec; a bare name one symbol carries resolves to it."""
- rows = [r for r in rows if not is_excluded(r.file_path, exclude_spec)]
- if not rows and "::" not in symbol_id:
- # A bare name one symbol carries is that symbol; several stay suggestions.
- async with get_session(ctx.session_factory) as session:
- named, complete = await _symbols_named(session, repository.id, symbol_id, exclude_spec)
- if complete and len(named) == 1:
- rows = await _resolve_symbol(session, repository.id, named[0])
- return rows
-
-
-def _live_grep_response(
- ctx: Any, repository: Any, symbol_id: str, exclude_spec: Any, t0: float
-) -> dict | None:
- """Live-file lines naming a symbol the index lacks (a constant, import or alias), else None."""
- file_part, name_part = _parse_symbol_id(symbol_id)
- if not file_part or not name_part or is_excluded(file_part, exclude_spec):
- return None
- matches = _live_grep_fallback(Path(str(ctx.path)), file_part, name_part)
- if not matches:
- return None
- likely = (
- "defined here, so likely added after the last index; "
- "run `repowise update` to index it"
- if any(m.get("defines") for m in matches)
- else "likely a constant, import, or alias"
- )
- return {
- "symbol_id": symbol_id,
- "file": file_part,
- "resolution": "live_grep",
- "fallback_lines": matches,
- "verified": True,
- "note": (
- "Not an indexed symbol, but the name matches these "
- f"live-file lines ({likely}). For surrounding source "
- f'use a range read: "{file_part}:<start>-<end>".'
- ),
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- repository=repository,
- targets=[file_part],
- ),
- }
-
-
-async def _not_found_response(
- ctx: Any, repository: Any, symbol_id: str, exclude_spec: Any, t0: float
-) -> dict:
- """Live lines, exact-id suggestions, or a not-found error for an index miss."""
- if ctx.path:
- live = _live_grep_response(ctx, repository, symbol_id, exclude_spec, t0)
- if live is not None:
- return live
- async with get_session(ctx.session_factory) as session:
- suggestions = await _symbol_suggestions(session, repository.id, symbol_id, exclude_spec)
- if suggestions:
- return {
- "symbol_id": symbol_id,
- "error": (
- f"Symbol not found: {symbol_id!r}. A symbol with this name "
- "exists at the path(s) below — retry with one of these "
- "exact symbol_ids."
- ),
- "suggestions": suggestions,
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- repository=repository,
- ),
- }
- return {
- "symbol_id": symbol_id,
- "error": (
- f"Symbol not found: {symbol_id!r}. Use get_context to list "
- "available symbols in the file, then try again with the "
- "exact symbol_id from that response."
- ),
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- repository=repository,
- ),
- }
-
-
-def _unreadable_source_response(row: Any, symbol_id: str, repository: Any, t0: float) -> dict:
- return {
- "symbol_id": symbol_id,
- "file": row.file_path,
- "name": row.name,
- "kind": row.kind,
- "signature": row.signature,
- "error": (
- "Symbol metadata exists but source file could not be read. "
- "The file may have been moved or deleted since indexing."
- ),
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- repository=repository,
- ),
- }
-
-
-class _ServedBody(NamedTuple):
- """The numbered lines served for one symbol, and the outline if it was outlined."""
-
- numbered: str
- start: int
- end: int
- truncated: bool
- outline: tuple[list[dict], int, int] | None
-
-
-async def _outline_if_large(
- ctx: Any, repository: Any, row: Any, text: str, check: Any
-) -> tuple[list[dict], int, int] | None:
- """Members outline of a verified container body too large to serve whole."""
- if row.kind not in _CONTAINER_KINDS or not check.verified:
- return None
- # Sized on the body alone, so context_lines never tips a class into an outline.
- bare, bare_start, _e, _t = _slice_text(text, check.start_line, check.end_line, 0)
- if len(_number_lines(bare, bare_start)) <= _OUTLINE_MIN_CHARS:
- return None
- return await _container_outline(
- ctx.session_factory, repository.id, row, text, check.start_line, check.end_line
- )
-
-
-async def _served_body(
- ctx: Any, repository: Any, row: Any, text: str, check: Any, context_lines: int
-) -> _ServedBody:
- """The body slice to serve: the whole body, a capped head, or a header plus outline."""
- source, start, end, _total = _slice_text(text, check.start_line, check.end_line, context_lines)
- numbered = _number_lines(source, start)
-
- truncated = (end - start + 1) >= _MAX_SOURCE_LINES and (
- check.end_line - check.start_line + 1 + 2 * context_lines
- ) > _MAX_SOURCE_LINES
-
- outline = await _outline_if_large(ctx, repository, row, text, check)
- if outline is None:
- return _ServedBody(numbered, start, end, truncated, None)
- _members, first_member, _members_total = outline
- header_end = min(first_member - 1, check.start_line + _OUTLINE_HEADER_LINES - 1, check.end_line)
- # context_lines widens the header upward only; below it are the members.
- source, start, end, _total = _slice_text(
- text,
- max(1, check.start_line - context_lines),
- max(check.start_line, header_end),
- 0,
- )
- source = source.rstrip()
- end = start + len(source.splitlines()) - 1 if source else start
- return _ServedBody(_number_lines(source, start), start, end, False, outline)
-
-
-def _note_outline(
- response: dict, outline: tuple[list[dict], int, int], row: Any, check: Any
-) -> None:
- """Mark an outlined body and say how to fetch its members or the whole body."""
- members, _first_member, members_total = outline
- # An outline is not the body, so it never claims ``_meta.complete``.
- response["outlined"] = True
- response["members"] = members
- response["note"] = (
- f"Body ({check.start_line}-{check.end_line}) outlined: header plus "
- f"{len(members)} members. Fetch one member with get_symbol on its "
- f"symbol_id, or Read {row.file_path} lines "
- f"{check.start_line}-{check.end_line} for the whole body."
- )
- if members_total > len(members):
- response["members_total"] = members_total
- last = members[-1]["end_line"] if members else check.start_line
- response["note"] += (
- f" {members_total - len(members)} more members are not listed;"
- f" they start after line {last}."
- )
-
-
-def _note_continuation(
- response: dict, body: _ServedBody, row: Any, check: Any, alias: Any
-) -> None:
- """Hand back the exact range read that fetches the rest of a capped body."""
- continuation_reference = source_reference(
- alias,
- row.file_path,
- lines=[body.end + 1, check.end_line],
- verification_basis="live",
- source_kind="source",
- )
- response["continuation"] = continuation_reference["id"]
- response["continuation_reference"] = continuation_reference
- response["note"] = (
- f"Symbol body ({check.start_line}-{check.end_line}) exceeds the "
- f"{_MAX_SOURCE_LINES}-line serve cap; served {body.start}-{body.end}. Fetch "
- f"the remainder in one call: get_symbol({response['continuation']!r})."
- )
-
-
-def _symbol_body_response(
- row: Any, check: Any, body: _ServedBody, repository: Any, alias: Any, t0: float
-) -> dict:
- """The served body with its outline, continuation and bounds notes."""
- response = {
- "symbol_id": symbol_identity(row.symbol_id),
- "file": row.file_path,
- "name": row.name,
- "kind": row.kind,
- "qualified_name": row.qualified_name,
- "signature": row.signature,
- "language": row.language,
- "start_line": body.start,
- "end_line": body.end,
- "symbol_start_line": check.start_line,
- "symbol_end_line": check.end_line,
- "source": body.numbered,
- "truncated": body.truncated,
- "verified": check.verified,
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- hint=_symbol_hint(row.symbol_id, check.end_line, check.start_line),
- repository=repository,
- # Served bytes are live-verified; only this file's drift matters.
- targets=[row.file_path],
- ),
- }
- if body.outline is not None:
- _note_outline(response, body.outline, row, check)
- elif not body.truncated and check.verified:
- # The whole body was served against live bytes, so nothing is left to
- # fetch for this symbol.
- response["_meta"]["complete"] = _completeness_line(bodies=1)
- if body.truncated and not check.approximate and body.end < check.end_line:
- _note_continuation(response, body, row, check, alias)
- if check.approximate:
- response["bounds"] = "approximate"
- response["note"] = (
- "The live file no longer contains this symbol at its indexed "
- "location and it could not be re-located by name — it may have "
- "been renamed or removed since indexing. The served slice is "
- "the indexed line range from the current file contents; verify "
- "before citing."
- )
- return response
-
-
-async def _serve_symbol(
- ctx: Any,
- repository: Any,
- row: Any,
- symbol_id: str,
- context_lines: int,
- depth: int,
- exclude_spec: Any,
- t0: float,
-) -> dict:
- """Live-verified body of one resolved symbol, with callee bodies past depth 1."""
- repo_root = Path(str(ctx.path))
- text = _read_file_text(repo_root, row.file_path)
- if text is None:
- return _unreadable_source_response(row, symbol_id, repository, t0)
-
- from repowise.core.distill.budget import estimate_tokens
-
- full_tokens = estimate_tokens(text)
-
- # Stored bounds are checked against the live file first: stale ones are
- # corrected and healed, unfindable ones served as approximate.
- check = check_symbol_bounds(row, text)
- if check.corrected:
- await heal_symbol_row(ctx.session_factory, row, check.start_line, check.end_line)
-
- body = await _served_body(ctx, repository, row, text, check, context_lines)
- response = _symbol_body_response(row, check, body, repository, ctx.alias, t0)
- # An outline answers for the shape; callee bodies would undo its size.
- if depth > 1 and body.outline is None:
- async with get_session(ctx.session_factory) as session:
- callee_block = await _expand_callees(
- session,
- repository.id,
- row,
- repo_root,
- depth,
- exclude_spec,
- ctx.alias,
- )
- if callee_block is not None:
- response["callee_bodies"] = callee_block
-
- # Serving one symbol replaced reading the whole file.
- from repowise.server.mcp_server._savings import declare_replaced
-
- declare_replaced(response, full_tokens)
- return response
-
-
-async def _indexed_symbol_read(
- ctx: Any, symbol_id: str, context_lines: int, depth: int, t0: float
-) -> dict:
- """Resolve *symbol_id* in the index and serve it, its candidates, or a miss."""
- context_lines = max(0, min(50, context_lines))
- # Clamped, not rejected: the deepest walk we do is the useful reply.
- depth = max(1, min(_MAX_CALLEE_DEPTH, depth))
-
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- rows = await _resolve_symbol(session, repository.id, symbol_id)
-
- # Before the exclusion spec: it is built from the repo path.
- if not ctx.path:
- return {
- "symbol_id": symbol_id,
- "error": "MCP server has no repo path configured",
- "_meta": _build_meta(
- timing_ms=_elapsed_ms(t0),
- repository=repository,
- ),
- }
-
- exclude_spec = _get_exclude_spec(ctx.path)
- rows = await _rows_in_scope(ctx, repository, symbol_id, rows, exclude_spec)
- if not rows:
- return await _not_found_response(ctx, repository, symbol_id, exclude_spec, t0)
- if len(rows) > 1:
- return await _render_ambiguous(rows, symbol_id, ctx, repository, t0, context_lines)
- return await _serve_symbol(
- ctx, repository, rows[0], symbol_id, context_lines, depth, exclude_spec, t0
- )
-
-
[email protected](surface_order=30, artifact_type="source", presentation="source", evidence_basis="measured")
-async def get_symbol(
- symbol_id: str | None = None,
- context_lines: int = 0,
- repo: str | None = None,
- query: str | None = None,
- id: str | None = None,
- depth: int = 1,
- reference: dict[str, Any] | None = None,
-) -> dict:
- """Follow-up read of one symbol whose id another response already gave you.
-
- **Not an entry point.** ``get_answer`` already ships ``symbol_bodies``, and
- for a whole file ``get_context(include=["skeleton"])`` or a plain Read is
- one call instead of many. Reach here for a body that was elided, or for a
- ``continuation`` / omission ref. Never walk a file symbol by symbol.
-
- Returns verified, line-numbered source for one indexed symbol, live range,
- or omission ref. Ambiguity returns every candidate; an index miss returns
- live fallback lines. A truncated result carries the exact continuation to
- pass straight back.
-
- Args:
- symbol_id: "path/to/file.py::Name", "path/to/file.py:140-180" for a
- 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. With
- no id given, it is read as ``symbol_id``.
- 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``.
- reference: structured source reference emitted by this tool. Its id
- and repository are accepted together without caller translation.
- """
- symbol_id, repo = _reference_arguments(reference, symbol_id, id, repo)
- if repo == "all":
- return _unsupported_repo_all("get_symbol")
- ctx = await _resolve_repo_context(repo)
-
- t0 = time.perf_counter()
- symbol_id, query = _requested_id(symbol_id, id, query)
- if not symbol_id or not symbol_id.strip():
- return {
- "symbol_id": symbol_id,
- "error": 'get_symbol requires `symbol_id`, e.g. "path/to/file.py::Name".',
- "_meta": _build_meta(timing_ms=_elapsed_ms(t0)),
- }
-
- omission_ref = _extract_omission_ref(symbol_id)
- if omission_ref is not None:
- canonical_omission = omission_reference(symbol_id) or symbol_id
- return _resolve_omission_ref(
- canonical_omission,
- omission_ref,
- query,
- ctx.path,
- t0,
- other_repo_roots() if repo is None else (),
- )
-
- if repo is None:
- routed = await _routed_read(symbol_id, context_lines, query, depth)
- if routed is not None:
- return routed
- ranged = await _range_id_read(symbol_id, context_lines, ctx, t0)
- if ranged is not None:
- return ranged
- return await _indexed_symbol_read(ctx, symbol_id, context_lines, depth, t0)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/__init__.py
new file mode 100644
index 000000000..b7f4d11a2
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/__init__.py
@@ -0,0 +1,191 @@
+"""MCP Tool: get_symbol — byte-precise source retrieval for a single symbol.
+
+This is the structural counterpart to get_context. Where get_context returns
+file-level narrative (summary, symbol list, importers), get_symbol returns
+the actual source bytes of one named symbol — function body, class body, or
+method — by slicing the on-disk source file using the line range stored on
+the WikiSymbol row at index time.
+
+Why a separate tool instead of "include source" on get_context?
+ * Granularity: a single function is ~30 lines vs a 300-line file. Cuts the
+ cached prompt prefix by ~10x when the agent only needs one symbol.
+ * Predictability: response size is bounded by the symbol size, never the
+ file size — no surprise 50 KB payloads.
+ * Verified bounds: the persisted line range is checked against the live
+ file before serving (name-on-definition-line gate); on mismatch the
+ file is re-parsed once, the bounds corrected and healed in the DB. A
+ ``verified: true`` response never needs a follow-up Read.
+
+The tool is intentionally additive — get_context remains the right call for
+"explain this file" or "what's the relationship between A and B" questions.
+get_symbol is for "show me the body of this function".
+
+Resolution strategy (in order):
+ 1. Exact match on WikiSymbol.symbol_id (the canonical "{path}::{name}" key)
+ 2. Exact match on (file_path, qualified_name) — supports class.method form
+ 3. Exact match on (file_path, name) — supports unqualified names
+ 4. Suffix match — a bare filename or partial path ("answer.py::get_answer")
+ resolves against any file whose path ends with that segment, on the leaf
+ name; mirrors get_context's basename ladder. A total miss returns
+ ``suggestions`` (real path-qualified ids) instead of a bare "not found".
+
+The tool also resolves **omission refs**: a ``symbol_id`` of the form
+``"repowise#<12-hex>"`` (from a ``[repowise#<ref>: ...]`` truncation marker)
+retrieves the omitted content from the durable omission store instead of the
+symbol index. The two id shapes are syntactically unambiguous — a real
+symbol_id always contains a file path — so dispatch is trivial and the
+symbol contract is untouched.
+
+Returns a flat dict (not wrapped in `targets`) so the agent can pipe the
+`source` field straight to its scratch buffer.
+
+``tool.py`` holds the registered tool; the sibling modules hold its stages.
+Every name the single module had is re-exported here, and a stage calls a
+name tests patch through the package (``_pkg.<name>``), never by bare name,
+or the patch stops reaching it.
+"""
+
+# ruff: noqa: F401
+
+from __future__ import annotations
+
+import functools
+import json
+import re
+import sqlite3
+import time
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, NamedTuple
+
+from sqlalchemy import select
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import WikiSymbol
+from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.server.mcp_server._budget import register_post_shed
+from repowise.server.mcp_server._budget.contracts import DEFAULT_RESPONSE_CHARS
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ _get_repo,
+ _is_workspace_mode,
+ _resolve_repo_context,
+ _unsupported_repo_all,
+ clean_signature,
+ 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 completeness_line as _completeness_line
+from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
+from repowise.server.mcp_server._references import (
+ omission_reference,
+ path_identity,
+ source_reference,
+ symbol_identity,
+)
+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,
+ parse_live_symbols,
+)
+from repowise.server.mcp_server._workspace_routing import (
+ hint_misses,
+ needs_routing,
+ other_repo_roots,
+ route_targets,
+)
+from repowise.server.mcp_server.tool_symbol.ambiguous import (
+ _AMBIGUITY_CHAR_BUDGET,
+ _correct_ambiguity_note,
+ _finish_ambiguous,
+ _render_ambiguous,
+)
+from repowise.server.mcp_server.tool_symbol.body import (
+ _CONTAINER_KINDS,
+ _OUTLINE_HEADER_LINES,
+ _OUTLINE_MEMBER_CHARS,
+ _OUTLINE_MIN_CHARS,
+ _OUTLINE_SUMMARY_CHARS,
+ _container_outline,
+ _note_continuation,
+ _note_outline,
+ _outline_if_large,
+ _serve_symbol,
+ _served_body,
+ _ServedBody,
+ _symbol_body_response,
+ _unreadable_source_response,
+)
+from repowise.server.mcp_server.tool_symbol.callees import (
+ _CALLEE_CHAR_BUDGET,
+ _MAX_CALLEE_BODY_LINES,
+ _MAX_CALLEE_DEPTH,
+ _MAX_CALLEES_PER_HOP,
+ _CalleeBody,
+ _CalleeHop,
+ _discover_callee_hops,
+ _expand_callees,
+ _partition_callees,
+ _prepare_callee_entries,
+ _render_callee,
+ _slice_callee_body,
+ _spend_callee_budget,
+ _unseen_callees_of,
+)
+from repowise.server.mcp_server.tool_symbol.lookup import (
+ _NAME_SCAN_CAP,
+ _NAME_SEPARATORS,
+ _bare_name,
+ _name_variants,
+ _order_candidates,
+ _parse_symbol_id,
+ _resolve_symbol,
+ _rows_in_scope,
+ _symbol_id_variants,
+ _symbol_suggestions,
+ _symbols_named,
+)
+from repowise.server.mcp_server.tool_symbol.misses import (
+ _COMMENT_PREFIXES,
+ _DEF_KEYWORDS,
+ _DEF_MODIFIERS,
+ _MAX_FALLBACK_MATCHES,
+ _live_grep_fallback,
+ _live_grep_response,
+ _not_found_response,
+)
+from repowise.server.mcp_server.tool_symbol.omission import (
+ _extract_omission_ref,
+ _resolve_omission_ref,
+)
+from repowise.server.mcp_server.tool_symbol.ranges import (
+ _MAX_RANGE_LINES,
+ _RANGE_ID_RE,
+ _range_id_read,
+ _resolve_range_read,
+)
+from repowise.server.mcp_server.tool_symbol.text import (
+ _MAX_SOURCE_LINES,
+ _elapsed_ms,
+ _number_lines,
+ _read_file_text,
+ _slice_text,
+)
+from repowise.server.mcp_server.tool_symbol.tool import (
+ _indexed_symbol_read,
+ _reference_arguments,
+ _requested_id,
+ _routed_read,
+ get_symbol,
+)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/ambiguous.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/ambiguous.py
new file mode 100644
index 000000000..9d0aa4d6f
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/ambiguous.py
@@ -0,0 +1,170 @@
+"""Ambiguous ids: every candidate body served in one response."""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Any
+
+from repowise.core.persistence.models import WikiSymbol
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._budget import register_post_shed
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._meta import completeness_line as _completeness_line
+from repowise.server.mcp_server._references import (
+ source_reference,
+ symbol_identity,
+)
+from repowise.server.mcp_server._verify import (
+ check_symbol_bounds,
+ heal_symbol_row,
+)
+
+from .text import _number_lines, _read_file_text, _slice_text
+
+# When a lookup is ambiguous (overloads, re-exports, conditional defs) every
+# candidate body is served in ONE response — a silently-picked wrong candidate
+# sends the agent into a read-spiral that costs far more than the extra bytes.
+# This caps the total candidate-source chars; the first candidate always
+# renders, the rest render while budget remains and are otherwise listed with
+# an exact range read that fetches them.
+_AMBIGUITY_CHAR_BUDGET = 20_000
+
+
+async def _render_ambiguous(
+ rows: list[WikiSymbol],
+ symbol_id: str,
+ ctx: Any,
+ repository: Any,
+ t0: float,
+ context_lines: int,
+) -> dict:
+ """Serve EVERY candidate body for an ambiguous symbol id in one response.
+
+ A deterministic-but-wrong pick reads as authoritative and sends the agent
+ editing the wrong overload; returning all candidates costs bytes once and
+ removes the guess. The first candidate always renders; the rest render
+ while the char budget lasts and are otherwise listed with the exact range
+ read that fetches them.
+ """
+ repo_root = Path(str(ctx.path))
+ text_cache: dict[str, str | None] = {}
+ candidates: list[dict] = []
+ not_rendered: list[dict] = []
+ remaining = _pkg._AMBIGUITY_CHAR_BUDGET
+ whole_bodies = 0
+
+ for i, row in enumerate(rows):
+ 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]
+
+ entry: dict[str, Any] = {
+ "symbol_id": symbol_identity(row.symbol_id),
+ "file": row.file_path,
+ "name": row.name,
+ "kind": row.kind,
+ "qualified_name": row.qualified_name,
+ "signature": row.signature,
+ }
+ if text is None:
+ entry["note"] = "source file could not be read"
+ not_rendered.append(entry)
+ continue
+
+ check = check_symbol_bounds(row, text)
+ if check.corrected:
+ await heal_symbol_row(ctx.session_factory, row, check.start_line, check.end_line)
+ source, start, end, _total = _slice_text(
+ text, check.start_line, check.end_line, context_lines
+ )
+ entry.update({"start_line": start, "end_line": end, "verified": check.verified})
+
+ numbered = _number_lines(source, start)
+ if i > 0 and len(numbered) > remaining:
+ fetch_reference = source_reference(
+ ctx.alias,
+ row.file_path,
+ lines=[start, end],
+ verification_basis="live",
+ source_kind="source",
+ )
+ entry["fetch_with"] = fetch_reference["id"]
+ entry["fetch_reference"] = fetch_reference
+ not_rendered.append(entry)
+ continue
+ remaining -= len(numbered)
+ entry["source"] = numbered
+ candidates.append(entry)
+ # A candidate is whole only when the served span reaches both ends of
+ # the verified bounds; a budget-clipped or relocated one does not count.
+ if check.verified and start <= check.start_line and end >= check.end_line:
+ whole_bodies += 1
+
+ response: dict[str, Any] = {
+ "symbol_id": symbol_id,
+ "ambiguous": True,
+ "match_count": len(rows),
+ "candidates": candidates,
+ "note": (
+ f"{len(rows)} symbols match this id (overloads, re-exports, or "
+ "conditional definitions). All candidate bodies are included — "
+ "none was silently chosen; pick by signature and line range."
+ ),
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ repository=repository,
+ targets=sorted({r.file_path for r in rows}),
+ ),
+ }
+ _finish_ambiguous(response, whole_bodies, not_rendered, text_cache)
+ return response
+
+
+def _finish_ambiguous(
+ response: dict[str, Any],
+ whole_bodies: int,
+ not_rendered: list[dict],
+ text_cache: dict[str, str | None],
+) -> None:
+ """Completeness, the not-rendered list and the replaced-read savings."""
+ if whole_bodies:
+ response["_meta"]["complete"] = _completeness_line(bodies=whole_bodies)
+ if not_rendered:
+ response["not_rendered"] = not_rendered
+ response["note"] += (
+ " Candidates over the response budget are listed in not_rendered —"
+ " fetch one via get_symbol with its fetch_with range."
+ )
+
+ from repowise.core.distill.budget import estimate_tokens
+ from repowise.server.mcp_server._savings import declare_replaced
+
+ full_tokens = sum(estimate_tokens(t) for t in text_cache.values() if t)
+ if full_tokens:
+ declare_replaced(response, full_tokens)
+
+
+def _correct_ambiguity_note(result: dict[str, Any], _collector: Any) -> None:
+ """Stop promising every candidate body once the budget has cut some.
+
+ The ambiguous shape exists so a wrong pick is never made silently, and says
+ so in ``note``. A shed that leaves the note standing makes exactly the
+ claim the shape was built to avoid.
+ """
+ if not result.get("ambiguous"):
+ return
+ emitted = result.get("candidates_emitted")
+ if emitted is None or emitted >= (result.get("match_count") or 0):
+ return
+ result["note"] = (
+ f"{result.get('match_count')} symbols match this id (overloads, "
+ f"re-exports, or conditional definitions). {emitted} candidate bodies "
+ "fit this response; the rest are recoverable from the omission ref, or "
+ "fetch one directly with its file range."
+ )
+
+
+register_post_shed("get_symbol", _correct_ambiguity_note)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py
new file mode 100644
index 000000000..51234477c
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/body.py
@@ -0,0 +1,323 @@
+"""One resolved symbol's served body: whole, capped, or outlined."""
+
+from __future__ import annotations
+
+import functools
+import json
+from pathlib import Path
+from typing import Any, NamedTuple
+
+from sqlalchemy import select
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import WikiSymbol
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._budget.contracts import DEFAULT_RESPONSE_CHARS
+from repowise.server.mcp_server._helpers import (
+ clean_signature,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._meta import completeness_line as _completeness_line
+from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
+from repowise.server.mcp_server._references import (
+ source_reference,
+ symbol_identity,
+)
+from repowise.server.mcp_server._verify import (
+ check_symbol_bounds,
+ heal_symbol_row,
+)
+
+from .text import _MAX_SOURCE_LINES, _elapsed_ms, _number_lines, _read_file_text, _slice_text
+
+# A container whose served body would exceed this is outlined instead: its
+# header plus each member's signature, lines and id. Half the default reply
+# budget, so smaller classes keep the one-call whole body, while a class big
+# enough to crowd out the rest of the reply is usually wanted for its shape.
+_OUTLINE_MIN_CHARS = DEFAULT_RESPONSE_CHARS // 2
+_CONTAINER_KINDS = frozenset({"class", "interface", "struct", "enum", "trait", "impl", "module"})
+# Header lines (decorators, declaration, docstring head) served above members.
+_OUTLINE_HEADER_LINES = 12
+_OUTLINE_SUMMARY_CHARS = 160
+# Serialized chars of member rows listed; the rest are counted in members_total.
+_OUTLINE_MEMBER_CHARS = DEFAULT_RESPONSE_CHARS // 2
+
+
+async def _container_outline(
+ session_factory: Any, repo_id: str, row: WikiSymbol, text: str, start: int, end: int
+) -> tuple[list[dict[str, Any]], int, int] | None:
+ """Direct members of the container *row* spanning ``start``-``end``, as outline rows.
+
+ Returns the listed rows (capped at ``_OUTLINE_MEMBER_CHARS``), the line the
+ first member starts on and the member total, or None when the index holds
+ no members to outline. Each member is verified against the live file,
+ parsing it at most once for the whole set.
+
+ Members are matched by parent name inside the container's own lines, so
+ Rust impl blocks and Go receiver methods declared outside a struct do not
+ outline it.
+ """
+ async with get_session(session_factory) as session:
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path == row.file_path,
+ WikiSymbol.parent_name == row.name,
+ WikiSymbol.id != row.id,
+ )
+ )
+ rows = list(res.scalars().all())
+ _parsed = functools.cache(lambda: _pkg.parse_live_symbols(row, text))
+ members: list[dict[str, Any]] = []
+ for member in rows:
+ check = check_symbol_bounds(member, text, _parsed)
+ # A same-named container elsewhere in the file shares the parent name;
+ # an unverified member is judged by its indexed range instead.
+ if check.approximate:
+ if not start <= member.start_line <= member.end_line <= end:
+ continue
+ elif not start <= check.start_line <= end:
+ continue
+ entry: dict[str, Any] = {
+ "symbol_id": symbol_identity(member.symbol_id),
+ "kind": member.kind,
+ "signature": clean_signature(member.signature),
+ "start_line": check.start_line,
+ "end_line": check.end_line,
+ }
+ summary = (member.docstring or "").strip().splitlines()
+ if summary:
+ entry["summary"] = summary[0][:_OUTLINE_SUMMARY_CHARS]
+ if check.approximate:
+ entry["bounds"] = "approximate"
+ members.append(entry)
+ if not members:
+ return None
+ members.sort(key=lambda m: m["start_line"])
+ # Overloads share one id, and get_symbol on it already serves every one.
+ unique: dict[str, dict[str, Any]] = {}
+ for entry in members:
+ unique.setdefault(entry["symbol_id"], entry)
+ members = list(unique.values())
+ first = min((m["start_line"] for m in members if "bounds" not in m), default=end + 1)
+ listed: list[dict[str, Any]] = []
+ remaining = _OUTLINE_MEMBER_CHARS
+ for entry in members:
+ remaining -= len(json.dumps(entry)) + 2
+ if remaining < 0:
+ break
+ listed.append(entry)
+ return listed, first, len(members)
+
+
+def _unreadable_source_response(row: Any, symbol_id: str, repository: Any, t0: float) -> dict:
+ return {
+ "symbol_id": symbol_id,
+ "file": row.file_path,
+ "name": row.name,
+ "kind": row.kind,
+ "signature": row.signature,
+ "error": (
+ "Symbol metadata exists but source file could not be read. "
+ "The file may have been moved or deleted since indexing."
+ ),
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ repository=repository,
+ ),
+ }
+
+
+class _ServedBody(NamedTuple):
+ """The numbered lines served for one symbol, and the outline if it was outlined."""
+
+ numbered: str
+ start: int
+ end: int
+ truncated: bool
+ outline: tuple[list[dict], int, int] | None
+
+
+async def _outline_if_large(
+ ctx: Any, repository: Any, row: Any, text: str, check: Any
+) -> tuple[list[dict], int, int] | None:
+ """Members outline of a verified container body too large to serve whole."""
+ if row.kind not in _CONTAINER_KINDS or not check.verified:
+ return None
+ # Sized on the body alone, so context_lines never tips a class into an outline.
+ bare, bare_start, _e, _t = _slice_text(text, check.start_line, check.end_line, 0)
+ if len(_number_lines(bare, bare_start)) <= _pkg._OUTLINE_MIN_CHARS:
+ return None
+ return await _container_outline(
+ ctx.session_factory, repository.id, row, text, check.start_line, check.end_line
+ )
+
+
+async def _served_body(
+ ctx: Any, repository: Any, row: Any, text: str, check: Any, context_lines: int
+) -> _ServedBody:
+ """The body slice to serve: the whole body, a capped head, or a header plus outline."""
+ source, start, end, _total = _slice_text(text, check.start_line, check.end_line, context_lines)
+ numbered = _number_lines(source, start)
+
+ truncated = (end - start + 1) >= _MAX_SOURCE_LINES and (
+ check.end_line - check.start_line + 1 + 2 * context_lines
+ ) > _MAX_SOURCE_LINES
+
+ outline = await _outline_if_large(ctx, repository, row, text, check)
+ if outline is None:
+ return _ServedBody(numbered, start, end, truncated, None)
+ _members, first_member, _members_total = outline
+ header_end = min(first_member - 1, check.start_line + _OUTLINE_HEADER_LINES - 1, check.end_line)
+ # context_lines widens the header upward only; below it are the members.
+ source, start, end, _total = _slice_text(
+ text,
+ max(1, check.start_line - context_lines),
+ max(check.start_line, header_end),
+ 0,
+ )
+ source = source.rstrip()
+ end = start + len(source.splitlines()) - 1 if source else start
+ return _ServedBody(_number_lines(source, start), start, end, False, outline)
+
+
+def _note_outline(
+ response: dict, outline: tuple[list[dict], int, int], row: Any, check: Any
+) -> None:
+ """Mark an outlined body and say how to fetch its members or the whole body."""
+ members, _first_member, members_total = outline
+ # An outline is not the body, so it never claims ``_meta.complete``.
+ response["outlined"] = True
+ response["members"] = members
+ response["note"] = (
+ f"Body ({check.start_line}-{check.end_line}) outlined: header plus "
+ f"{len(members)} members. Fetch one member with get_symbol on its "
+ f"symbol_id, or Read {row.file_path} lines "
+ f"{check.start_line}-{check.end_line} for the whole body."
+ )
+ if members_total > len(members):
+ response["members_total"] = members_total
+ last = members[-1]["end_line"] if members else check.start_line
+ response["note"] += (
+ f" {members_total - len(members)} more members are not listed;"
+ f" they start after line {last}."
+ )
+
+
+def _note_continuation(
+ response: dict, body: _ServedBody, row: Any, check: Any, alias: Any
+) -> None:
+ """Hand back the exact range read that fetches the rest of a capped body."""
+ continuation_reference = source_reference(
+ alias,
+ row.file_path,
+ lines=[body.end + 1, check.end_line],
+ verification_basis="live",
+ source_kind="source",
+ )
+ response["continuation"] = continuation_reference["id"]
+ response["continuation_reference"] = continuation_reference
+ response["note"] = (
+ f"Symbol body ({check.start_line}-{check.end_line}) exceeds the "
+ f"{_MAX_SOURCE_LINES}-line serve cap; served {body.start}-{body.end}. Fetch "
+ f"the remainder in one call: get_symbol({response['continuation']!r})."
+ )
+
+
+def _symbol_body_response(
+ row: Any, check: Any, body: _ServedBody, repository: Any, alias: Any, t0: float
+) -> dict:
+ """The served body with its outline, continuation and bounds notes."""
+ response = {
+ "symbol_id": symbol_identity(row.symbol_id),
+ "file": row.file_path,
+ "name": row.name,
+ "kind": row.kind,
+ "qualified_name": row.qualified_name,
+ "signature": row.signature,
+ "language": row.language,
+ "start_line": body.start,
+ "end_line": body.end,
+ "symbol_start_line": check.start_line,
+ "symbol_end_line": check.end_line,
+ "source": body.numbered,
+ "truncated": body.truncated,
+ "verified": check.verified,
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ hint=_symbol_hint(row.symbol_id, check.end_line, check.start_line),
+ repository=repository,
+ # Served bytes are live-verified; only this file's drift matters.
+ targets=[row.file_path],
+ ),
+ }
+ if body.outline is not None:
+ _note_outline(response, body.outline, row, check)
+ elif not body.truncated and check.verified:
+ # The whole body was served against live bytes, so nothing is left to
+ # fetch for this symbol.
+ response["_meta"]["complete"] = _completeness_line(bodies=1)
+ if body.truncated and not check.approximate and body.end < check.end_line:
+ _note_continuation(response, body, row, check, alias)
+ if check.approximate:
+ response["bounds"] = "approximate"
+ response["note"] = (
+ "The live file no longer contains this symbol at its indexed "
+ "location and it could not be re-located by name — it may have "
+ "been renamed or removed since indexing. The served slice is "
+ "the indexed line range from the current file contents; verify "
+ "before citing."
+ )
+ return response
+
+
+async def _serve_symbol(
+ ctx: Any,
+ repository: Any,
+ row: Any,
+ symbol_id: str,
+ context_lines: int,
+ depth: int,
+ exclude_spec: Any,
+ t0: float,
+) -> dict:
+ """Live-verified body of one resolved symbol, with callee bodies past depth 1."""
+ repo_root = Path(str(ctx.path))
+ text = _read_file_text(repo_root, row.file_path)
+ if text is None:
+ return _unreadable_source_response(row, symbol_id, repository, t0)
+
+ from repowise.core.distill.budget import estimate_tokens
+
+ full_tokens = estimate_tokens(text)
+
+ # Stored bounds are checked against the live file first: stale ones are
+ # corrected and healed, unfindable ones served as approximate.
+ check = check_symbol_bounds(row, text)
+ if check.corrected:
+ await heal_symbol_row(ctx.session_factory, row, check.start_line, check.end_line)
+
+ body = await _served_body(ctx, repository, row, text, check, context_lines)
+ response = _symbol_body_response(row, check, body, repository, ctx.alias, t0)
+ # An outline answers for the shape; callee bodies would undo its size.
+ if depth > 1 and body.outline is None:
+ async with get_session(ctx.session_factory) as session:
+ callee_block = await _pkg._expand_callees(
+ session,
+ repository.id,
+ row,
+ repo_root,
+ depth,
+ exclude_spec,
+ ctx.alias,
+ )
+ if callee_block is not None:
+ response["callee_bodies"] = callee_block
+
+ # Serving one symbol replaced reading the whole file.
+ from repowise.server.mcp_server._savings import declare_replaced
+
+ declare_replaced(response, full_tokens)
+ return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/callees.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/callees.py
new file mode 100644
index 000000000..18277bc7e
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/callees.py
@@ -0,0 +1,353 @@
+"""Callee expansion: call-graph bodies served beside the root symbol."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, NamedTuple
+
+from sqlalchemy import select
+
+from repowise.core.persistence.models import WikiSymbol
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._helpers import (
+ clean_signature,
+)
+from repowise.server.mcp_server._references import (
+ source_reference,
+ symbol_identity,
+)
+from repowise.server.mcp_server._verify import (
+ check_symbol_bounds,
+)
+
+from .text import _number_lines, _read_file_text, _slice_text
+
+# 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; 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 and across the whole
+# frontier, not per node.
+_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
+
+
+class _CalleeHop(NamedTuple):
+ """One hop of the walk: its true graph distance and the rows it produced.
+
+ ``over_cap`` counts rows the per-hop fan-out cap dropped. They are reported
+ as a number rather than as entries: listing them individually is the payload
+ the cap exists to prevent, and saying nothing would make a silent cut out of
+ a bound this module otherwise always makes recoverable. It is a floor over
+ the indexed graph, not a total — the per-node edge query carries its own
+ limit, so callees it never returned are not counted here either.
+ """
+
+ number: int
+ rows: list[WikiSymbol]
+ over_cap: int
+
+
+class _CalleeBody(NamedTuple):
+ """One callee's rendered body, sliced once and costed by its own length.
+
+ ``declared_*`` are the bounds the verified row claims; ``start``/``end`` are
+ what the line cap actually served, so ``end < declared_end`` is exactly the
+ truncation case.
+ """
+
+ source: str
+ start: int
+ end: int
+ declared_start: int
+ declared_end: int
+ verified: bool
+
+
+def _slice_callee_body(row: WikiSymbol, text: str) -> _CalleeBody:
+ """Slice *row* out of *text* under the callee line cap.
+
+ 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
+ )
+ return _CalleeBody(
+ source=_number_lines(source, start),
+ start=start,
+ end=end,
+ declared_start=check.start_line,
+ declared_end=check.end_line,
+ verified=check.verified,
+ )
+
+
+async def _unseen_callees_of(
+ session,
+ repo_id: str,
+ frontier: list[str],
+ seen: set[str],
+) -> tuple[list[str], dict[str, float]]:
+ """Call targets of *frontier* not already in *seen*, with their confidence.
+
+ Mutates *seen*, which is what keeps a diamond from being walked twice.
+ Edges below the confidence floor are dropped here: tier-3 resolution
+ invents edges, and a guessed one drags a whole unrelated body into the
+ payload.
+ """
+ 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,
+ )
+
+ next_ids: list[str] = []
+ confidence_of: dict[str, float] = {}
+ 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 or e.target_node_id in seen:
+ continue
+ seen.add(e.target_node_id)
+ next_ids.append(e.target_node_id)
+ confidence_of[e.target_node_id] = e.confidence or 0
+ return next_ids, confidence_of
+
+
+async def _discover_callee_hops(
+ session,
+ repo_id: str,
+ root_row: WikiSymbol,
+ depth: int,
+ exclude_spec: Any,
+) -> list[_CalleeHop]:
+ """Walk the call graph and return the rows of each hop, no bodies read.
+
+ Discovery is separate from rendering so the renderer knows, before it
+ spends the first character, how many hops actually produced rows. Reserving
+ a slice of the budget for a hop that turns out to be empty costs a body
+ that would otherwise have been served.
+
+ 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 reached at most once, at the
+ shallowest depth that reaches it, which keeps a diamond in the call graph
+ from being serialised twice. A symbol past the per-hop fan-out cap is not
+ re-offered at a deeper hop: it would then be labelled with a distance that
+ is not its own. It is counted in ``over_cap`` instead.
+ """
+ seen: set[str] = {root_row.symbol_id}
+ frontier = [root_row.symbol_id]
+ hops: list[_CalleeHop] = []
+
+ for hop_number in range(1, depth):
+ if not frontier:
+ break
+ next_ids, confidence_of = await _unseen_callees_of(session, repo_id, frontier, seen)
+ 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 _pkg.is_excluded(r.file_path, exclude_spec)]
+ # One hop, not one frontier node. Cut after the row lookup and the
+ # exclusion filter, so a dangling edge or an excluded path cannot spend
+ # a slot, and ranked by edge confidence as ``get_graph_edges_for_node``.
+ rows.sort(key=lambda r: (-confidence_of.get(r.symbol_id or "", 0.0), r.symbol_id or ""))
+ over_cap = max(len(rows) - _MAX_CALLEES_PER_HOP, 0)
+ rows = rows[:_MAX_CALLEES_PER_HOP]
+ # 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 ""))
+ if rows:
+ # The hop number is carried, not inferred from the position in this
+ # list: a hop whose rows were all excluded or all dangling would
+ # otherwise renumber every hop behind it, and a grandchild would be
+ # served claiming to be a direct callee.
+ hops.append(_CalleeHop(number=hop_number, rows=rows, over_cap=over_cap))
+ frontier = next_ids
+
+ return hops
+
+
+def _prepare_callee_entries(
+ hops: list[_CalleeHop], repo_root: Path
+) -> list[tuple[dict[str, Any], str, _CalleeBody | None]]:
+ """One ordered record per discovered row: ``(entry, file_path, body)``.
+
+ ``body`` is None when the file could not be read. The order is fixed here,
+ so the later refill pass cannot reshuffle the payload, and each body is
+ sliced exactly once, so what a body costs and what is emitted for it can
+ never disagree.
+ """
+ text_cache: dict[str, str | None] = {}
+ prepared: list[tuple[dict[str, Any], str, _CalleeBody | None]] = []
+ for hop in hops:
+ for row in hop.rows:
+ entry: dict[str, Any] = {
+ "symbol_id": symbol_identity(row.symbol_id),
+ "name": row.name,
+ "file": row.file_path,
+ "kind": row.kind,
+ "signature": clean_signature(row.signature),
+ "depth": hop.number,
+ }
+ 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]
+ body = None if text is None else _slice_callee_body(row, text)
+ prepared.append((entry, row.file_path, body))
+ return prepared
+
+
+def _render_callee(
+ entry: dict[str, Any], file_path: str, body: _CalleeBody, repository: str
+) -> None:
+ """Put *body* on *entry*, with the continuation read when the line cap cut it."""
+ entry.update(
+ {
+ "start_line": body.start,
+ "end_line": body.end,
+ "source": body.source,
+ "verified": body.verified,
+ }
+ )
+ if body.end < body.declared_end:
+ entry["truncated"] = True
+ continuation_reference = source_reference(
+ repository,
+ file_path,
+ lines=[body.end + 1, body.declared_end],
+ verification_basis="live",
+ source_kind="source",
+ )
+ entry["continuation"] = continuation_reference["id"]
+ entry["continuation_reference"] = continuation_reference
+
+
+def _spend_callee_budget(
+ hops: list[_CalleeHop],
+ prepared: list[tuple[dict[str, Any], str, _CalleeBody | None]],
+ repository: str,
+) -> None:
+ """Render the bodies the character budget covers, a per-hop share first."""
+ remaining = _pkg._CALLEE_CHAR_BUDGET
+ reserve_per_hop = _pkg._CALLEE_CHAR_BUDGET // len(hops)
+ # Pass 1: every hop spends its own share and no more, including the last
+ # (a cap, not a floor), so unspent budget cannot flow to deeper hops ahead
+ # of a deferred direct callee. Pass 2 redistributes leftovers in hop order.
+ for hop in hops:
+ spendable = min(reserve_per_hop, remaining)
+ for entry, file_path, body in prepared:
+ if entry["depth"] != hop.number or body is None or "source" in entry:
+ continue
+ if len(body.source) > spendable:
+ continue
+ _render_callee(entry, file_path, body, repository)
+ remaining -= len(body.source)
+ spendable -= len(body.source)
+
+ # Pass 2: a reserve nobody claimed goes back to whatever it deferred, in
+ # hop order, so an empty deeper hop costs the caller nothing.
+ for entry, file_path, body in prepared:
+ if body is None or "source" in entry or len(body.source) > remaining:
+ continue
+ _render_callee(entry, file_path, body, repository)
+ remaining -= len(body.source)
+
+
+def _partition_callees(
+ prepared: list[tuple[dict[str, Any], str, _CalleeBody | None]], repository: str
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Rendered entries, and the rest with the reason or the read that fetches them."""
+ entries: list[dict[str, Any]] = []
+ omitted: list[dict[str, Any]] = []
+ for entry, file_path, body in prepared:
+ if "source" in entry:
+ entries.append(entry)
+ elif body is None:
+ entry["note"] = "source file could not be read"
+ omitted.append(entry)
+ else:
+ # Out of budget: name the read that fetches it rather than
+ # dropping the symbol silently.
+ fetch_reference = source_reference(
+ repository,
+ file_path,
+ lines=[body.declared_start, body.declared_end],
+ verification_basis="live",
+ source_kind="source",
+ )
+ entry["fetch_with"] = fetch_reference["id"]
+ entry["fetch_reference"] = fetch_reference
+ omitted.append(entry)
+ return entries, omitted
+
+
+async def _expand_callees(
+ session,
+ repo_id: str,
+ root_row: WikiSymbol,
+ repo_root: Path,
+ depth: int,
+ exclude_spec: Any,
+ repository: str = "default",
+) -> dict[str, Any] | None:
+ """Breadth-first walk of the call graph from *root_row*, bodies included.
+
+ Bodies are served against a per-hop share of the character budget rather
+ than in loop order, so large direct callees cannot starve the deeper hops
+ the caller asked for. The reservation is taken only across hops that
+ discovery found rows for, and whatever the reserve leaves unspent is
+ refilled to the bodies it deferred, in hop order, so a direct callee is
+ first in line for a share the deeper hops did not use.
+
+ Returns None when the root has no outbound call edges, so the caller adds
+ no empty block to an ordinary response.
+ """
+ hops = await _discover_callee_hops(session, repo_id, root_row, depth, exclude_spec)
+ if not hops:
+ return None
+
+ prepared = _prepare_callee_entries(hops, repo_root)
+ _spend_callee_budget(hops, prepared, repository)
+ entries, omitted = _partition_callees(prepared, repository)
+
+ block: dict[str, Any] = {"depth": depth, "callees": entries}
+ fan_out_capped = [
+ {"depth": hop.number, "omitted": hop.over_cap} for hop in hops if hop.over_cap
+ ]
+ if fan_out_capped:
+ block["fan_out_capped"] = fan_out_capped
+ 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
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/lookup.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/lookup.py
new file mode 100644
index 000000000..57a0febfc
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/lookup.py
@@ -0,0 +1,89 @@
+"""Index lookups: the shared id grammar, name scans and suggestions."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from sqlalchemy import select
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import WikiSymbol
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+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,
+)
+
+# Rows read when matching a name across files. A scan that fills it is not
+# exhaustive, so its single survivor is never taken as the only match.
+_NAME_SCAN_CAP = 20
+
+
+# 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 _symbols_named(
+ session, repo_id: str, symbol_id: str, exclude_spec
+) -> tuple[list[str], bool]:
+ """Non-excluded ids of symbols carrying the name in *symbol_id*.
+
+ The second value says whether the scan saw every row with that name, so a
+ caller can tell "exactly one" from "one survivor of a capped scan".
+ """
+ qualified = "::" in symbol_id
+ # A bare name is matched whole: it has no path half to strip.
+ name = _parse_symbol_id(symbol_id)[1] if qualified else symbol_id.strip()
+ if not name:
+ return [], True
+ bare = _bare_name(name) if qualified else name
+ res = await session.execute(
+ select(WikiSymbol.symbol_id, WikiSymbol.file_path)
+ .where(WikiSymbol.repository_id == repo_id, WikiSymbol.name == bare)
+ .order_by(WikiSymbol.symbol_id)
+ .limit(_NAME_SCAN_CAP)
+ )
+ rows = res.all()
+ ids = [sid for sid, fpath in rows if sid and not _pkg.is_excluded(fpath, exclude_spec)]
+ return list(dict.fromkeys(ids)), len(rows) < _NAME_SCAN_CAP
+
+
+async def _symbol_suggestions(session, repo_id: str, symbol_id: str, exclude_spec) -> list[str]:
+ """Concrete symbol_ids to retry when a lookup misses entirely.
+
+ The caller usually had the right leaf name but a wrong or partial path.
+ Match that name across every file and hand back real ids (path-qualified)
+ the agent can pass straight back to get_symbol — a bare "not found" would
+ otherwise send it to get_context or a whole-file Read.
+ """
+ ids, _ = await _symbols_named(session, repo_id, symbol_id, exclude_spec)
+ return ids[:5]
+
+
+async def _rows_in_scope(
+ ctx: Any, repository: Any, symbol_id: str, rows: list[Any], exclude_spec: Any
+) -> list[Any]:
+ """*rows* outside the exclusion spec; a bare name one symbol carries resolves to it."""
+ rows = [r for r in rows if not _pkg.is_excluded(r.file_path, exclude_spec)]
+ if not rows and "::" not in symbol_id:
+ # A bare name one symbol carries is that symbol; several stay suggestions.
+ async with get_session(ctx.session_factory) as session:
+ named, complete = await _symbols_named(session, repository.id, symbol_id, exclude_spec)
+ if complete and len(named) == 1:
+ rows = await _resolve_symbol(session, repository.id, named[0])
+ return rows
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py
new file mode 100644
index 000000000..b6c5080de
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/misses.py
@@ -0,0 +1,134 @@
+"""Index misses: live-file grep lines, retry suggestions or not-found."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any
+
+from repowise.core.persistence.database import get_session
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+
+from .lookup import _bare_name, _parse_symbol_id, _symbol_suggestions
+from .text import _elapsed_ms, _number_lines, _read_file_text
+
+# Dead-end recovery: max grep matches returned when a symbol lookup misses
+# but the file exists on disk.
+_MAX_FALLBACK_MATCHES = 8
+
+# A matched line that declares the name rather than using it: a definition
+# keyword at line start, after decorators and modifiers. Keyword-based, so a
+# definition without one (``const f = () =>``) reads as a plain match.
+_DEF_KEYWORDS = r"(?:def|class|function\*?|func|fn|struct|interface|enum|trait|type|module|sub)"
+_DEF_MODIFIERS = (
+ r"(?:(?:export|default|pub(?:\([^)]*\))?|public|private|protected|internal|static"
+ r"|abstract|final|override|virtual|async|unsafe|extern|inline|open|sealed|partial|data)\s+)*"
+)
+_COMMENT_PREFIXES = ("#", "//", "/*", "*", "--", ";")
+
+
+def _live_grep_fallback(repo_root: Path, file_path: str, name: str) -> list[dict]:
+ """Find ``name`` in the live file when the symbol index misses.
+
+ Turns a dead-end call (pure cost) into an answer: constants, imports,
+ aliases, and decorators live between indexed symbols, and the line that
+ defines them is usually all the agent needs. ±2 lines of context per
+ match, capped at _MAX_FALLBACK_MATCHES.
+ """
+ text = _read_file_text(repo_root, file_path)
+ if text is None:
+ return []
+ bare = _bare_name(name)
+ if not bare:
+ return []
+ defines = re.compile(
+ rf"^\s*(?:@\S+\s+)*{_DEF_MODIFIERS}{_DEF_KEYWORDS}\s+(?:\([^)]*\)\s*)?{re.escape(bare)}\b"
+ )
+ lines = text.splitlines()
+ matches: list[dict] = []
+ for i, line in enumerate(lines, 1):
+ if bare in line:
+ lo, hi = max(1, i - 2), min(len(lines), i + 2)
+ match = {"line": i, "context": _number_lines("\n".join(lines[lo - 1 : hi]), lo)}
+ if not line.lstrip().startswith(_COMMENT_PREFIXES) and defines.match(line):
+ match["defines"] = True
+ matches.append(match)
+ if len(matches) >= _MAX_FALLBACK_MATCHES:
+ break
+ return matches
+
+
+def _live_grep_response(
+ ctx: Any, repository: Any, symbol_id: str, exclude_spec: Any, t0: float
+) -> dict | None:
+ """Live-file lines naming a symbol the index lacks (a constant, import or alias), else None."""
+ file_part, name_part = _parse_symbol_id(symbol_id)
+ if not file_part or not name_part or _pkg.is_excluded(file_part, exclude_spec):
+ return None
+ matches = _live_grep_fallback(Path(str(ctx.path)), file_part, name_part)
+ if not matches:
+ return None
+ likely = (
+ "defined here, so likely added after the last index; "
+ "run `repowise update` to index it"
+ if any(m.get("defines") for m in matches)
+ else "likely a constant, import, or alias"
+ )
+ return {
+ "symbol_id": symbol_id,
+ "file": file_part,
+ "resolution": "live_grep",
+ "fallback_lines": matches,
+ "verified": True,
+ "note": (
+ "Not an indexed symbol, but the name matches these "
+ f"live-file lines ({likely}). For surrounding source "
+ f'use a range read: "{file_part}:<start>-<end>".'
+ ),
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ repository=repository,
+ targets=[file_part],
+ ),
+ }
+
+
+async def _not_found_response(
+ ctx: Any, repository: Any, symbol_id: str, exclude_spec: Any, t0: float
+) -> dict:
+ """Live lines, exact-id suggestions, or a not-found error for an index miss."""
+ if ctx.path:
+ live = _live_grep_response(ctx, repository, symbol_id, exclude_spec, t0)
+ if live is not None:
+ return live
+ async with get_session(ctx.session_factory) as session:
+ suggestions = await _symbol_suggestions(session, repository.id, symbol_id, exclude_spec)
+ if suggestions:
+ return {
+ "symbol_id": symbol_id,
+ "error": (
+ f"Symbol not found: {symbol_id!r}. A symbol with this name "
+ "exists at the path(s) below — retry with one of these "
+ "exact symbol_ids."
+ ),
+ "suggestions": suggestions,
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ repository=repository,
+ ),
+ }
+ return {
+ "symbol_id": symbol_id,
+ "error": (
+ f"Symbol not found: {symbol_id!r}. Use get_context to list "
+ "available symbols in the file, then try again with the "
+ "exact symbol_id from that response."
+ ),
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ repository=repository,
+ ),
+ }
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py
new file mode 100644
index 000000000..01e94b9c8
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/omission.py
@@ -0,0 +1,100 @@
+"""Omission refs: content a truncation marker left in the omission store."""
+
+from __future__ import annotations
+
+import sqlite3
+import time
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+
+
+def _extract_omission_ref(symbol_id: str) -> str | None:
+ """Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""
+ from repowise.server.mcp_server._references import omission_reference
+
+ canonical = omission_reference(symbol_id)
+ return canonical.removeprefix("repowise#") if canonical else None
+
+
+def _resolve_omission_ref(
+ symbol_id: str,
+ ref: str,
+ query: str | None,
+ repo_root: Any,
+ t0: float,
+ other_roots: Sequence[tuple[str, Path]] = (),
+) -> dict:
+ """Look *ref* up in the omission store(s) and shape a tool response.
+
+ Checks the repo-local store first, then the stores of *other_roots* (the
+ other workspace repos, whose responses write their own), then the
+ user-level fallback — the same order as ``repowise expand``. Stores are
+ only opened when the DB file already exists (opening would otherwise
+ create an empty one). A ref is a content hash, so the first store holding
+ it has the content.
+ """
+ from repowise.core.distill.store import OmissionStore, default_store_path
+
+ canonical_ref = f"repowise#{ref}"
+ candidates: list[tuple[str | None, Path]] = []
+ if repo_root:
+ candidates.append((None, default_store_path(Path(str(repo_root)))))
+ for alias, root in other_roots:
+ candidates.append((alias, default_store_path(root)))
+ home_store = default_store_path(Path.home())
+ if home_store not in {path for _alias, path in candidates}:
+ candidates.append((None, home_store))
+
+ record: dict | None = None
+ found_in: str | None = None
+ for alias, db_path in candidates:
+ try:
+ if not db_path.exists():
+ continue
+ store = OmissionStore(db_path)
+ try:
+ record = store.get_record(ref, query=query)
+ finally:
+ store.close()
+ except (OSError, sqlite3.Error):
+ # An inaccessible fallback store is equivalent to a missing ref.
+ # Recovery must never make get_symbol itself fail.
+ continue
+ if record is not None:
+ found_in = alias
+ break
+
+ if record is None:
+ return {
+ "symbol_id": symbol_id,
+ "ref": canonical_ref,
+ "error": (
+ f"No stored content for omission ref {ref!r} — it may have "
+ "expired (7-day TTL), been pruned, or been produced in a "
+ "different repo. Re-run the original call for fresh content."
+ ),
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+
+ created = record.get("created_at")
+ response: dict[str, Any] = {
+ **({"repo": found_in} if found_in else {}),
+ "symbol_id": symbol_id,
+ "ref": canonical_ref,
+ "kind": "omission",
+ "source": record.get("source"),
+ "original_tokens": record.get("original_tokens"),
+ "content": record.get("content"),
+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),
+ }
+ if isinstance(created, (int, float)):
+ response["created_at"] = datetime.fromtimestamp(created, tz=UTC).isoformat()
+ if query is not None:
+ response["query"] = query
+ if not record.get("content"):
+ response["note"] = "No lines matched the query; omit query for the full content."
+ return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/ranges.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/ranges.py
new file mode 100644
index 000000000..0a0779358
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/ranges.py
@@ -0,0 +1,152 @@
+"""Live line-range reads: ``path/to/file.py:140-180`` ids."""
+
+from __future__ import annotations
+
+import re
+import time
+from pathlib import Path
+from typing import Any
+
+from repowise.core.persistence.database import get_session
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ _get_repo,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._meta import completeness_line as _completeness_line
+from repowise.server.mcp_server._references import (
+ path_identity,
+ source_reference,
+)
+
+from .text import _number_lines, _read_file_text, _slice_text
+
+# Range-read dispatch: "path/to/file.py:140-180". A single colon followed by
+# a numeric range never collides with "{path}::{name}" (double colon) or an
+# omission ref. The escape hatch for everything not indexed as a symbol —
+# imports, module docstrings, decorators between symbols — without falling
+# back to a whole-file Read.
+_RANGE_ID_RE = re.compile(r"^(?P<path>.+?):(?P<start>\d+)-(?P<end>\d+)$")
+
+# Range reads are bounded tighter than symbol reads: the caller names exact
+# lines, so a large range is a deliberate choice to cap.
+_MAX_RANGE_LINES = 200
+
+
+async def _resolve_range_read(
+ symbol_id: str, path: str, start: int, end: int, context_lines: int, ctx: Any, t0: float
+) -> dict:
+ """Serve a live, bounded line-range read: "path/to/file.py:140-180".
+
+ Always ``verified: true`` — the bytes come straight from the live file
+ at the requested lines. Bounded to _MAX_RANGE_LINES; the full-file token
+ count is declared as the counterfactual (the Read this call replaced).
+ """
+ repository = None
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+
+ def _err(msg: str) -> dict:
+ return {
+ "symbol_id": symbol_id,
+ "error": msg,
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000, repository=repository
+ ),
+ }
+
+ # Before the exclusion spec: it is built from the repo path.
+ if not ctx.path:
+ return _err("MCP server has no repo path configured")
+ if _pkg.is_excluded(path, _get_exclude_spec(ctx.path)):
+ return _err(f"'{path}' is excluded from indexing.")
+
+ text = _read_file_text(Path(str(ctx.path)), path)
+ if text is None:
+ return _err(f"File could not be read: {path!r}")
+
+ from repowise.core.distill.budget import estimate_tokens
+
+ full_tokens = estimate_tokens(text)
+
+ if end < start:
+ start, end = end, start
+ requested_end = end
+ requested_truncated = (end - start + 1) > _MAX_RANGE_LINES
+ if requested_truncated:
+ end = start + _MAX_RANGE_LINES - 1
+
+ # Cap the served span at _MAX_RANGE_LINES *including* context expansion —
+ # the docstring promises ≤200 lines, so context_lines must not push past
+ # it. Truncated reflects either an oversized request or a context-clipped
+ # span.
+ source, s, e, total = _slice_text(text, start, end, context_lines, max_lines=_MAX_RANGE_LINES)
+ range_truncated = requested_truncated or (e - s + 1) >= _MAX_RANGE_LINES
+
+ response = {
+ "symbol_id": symbol_id,
+ "file": path,
+ "kind": "range",
+ "start_line": s,
+ "end_line": e,
+ "total_lines": total,
+ "source": _number_lines(source, s),
+ "truncated": range_truncated,
+ "verified": True,
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ repository=repository,
+ # A range read serves live bytes; index drift elsewhere is noise.
+ targets=[path],
+ ),
+ }
+ if s == 1 and e == total and not range_truncated:
+ # Only a range that covers the file end to end is a whole unit; any
+ # other slice leaves lines the caller still has to go and read.
+ response["_meta"]["complete"] = _completeness_line(files=1)
+ remainder_end = min(requested_end, total)
+ if range_truncated and e < remainder_end:
+ # Same clean-continuation contract as a truncated symbol read: name the
+ # exact next range instead of leaving the agent to guess it.
+ continuation_reference = source_reference(
+ ctx.alias,
+ path,
+ lines=[e + 1, remainder_end],
+ verification_basis="live",
+ source_kind="source",
+ )
+ response["continuation"] = continuation_reference["id"]
+ response["continuation_reference"] = continuation_reference
+ response["note"] = (
+ f"Range capped at {_MAX_RANGE_LINES} lines; served {s}-{e}. "
+ f"Continue in one call: get_symbol({response['continuation']!r})."
+ )
+ from repowise.server.mcp_server._savings import declare_replaced
+
+ declare_replaced(response, full_tokens)
+ return response
+
+
+async def _range_id_read(symbol_id: str, context_lines: int, ctx: Any, t0: float) -> dict | None:
+ """A live range read for a ``path:start-end`` id, else None."""
+ range_match = _RANGE_ID_RE.match(symbol_id.strip())
+ if not range_match or "::" in symbol_id:
+ return None
+ normalized_path = path_identity(range_match.group("path"))
+ range_start = int(range_match.group("start"))
+ range_end = int(range_match.group("end"))
+ if range_end < range_start:
+ range_start, range_end = range_end, range_start
+ normalized_id = f"{normalized_path}:{range_start}-{range_end}"
+ return await _resolve_range_read(
+ normalized_id,
+ normalized_path,
+ range_start,
+ range_end,
+ max(0, min(50, context_lines)),
+ ctx,
+ t0,
+ )
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/text.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/text.py
new file mode 100644
index 000000000..28a644d7a
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/text.py
@@ -0,0 +1,71 @@
+"""Live file text: reading, slicing and Read-style line numbering."""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+from repowise.server.mcp_server._helpers import (
+ read_repo_file_text,
+)
+
+_log = __import__("logging").getLogger("repowise.mcp.symbol")
+
+
+# Safety cap so a misconfigured WikiSymbol row pointing at a giant file can
+# never blow up the agent's context window. Nearly every symbol fits, so one
+# call serves the whole body; the rare overflow gets a clean `continuation`.
+_MAX_SOURCE_LINES = 600
+
+
+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."""
+ 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(
+ text: str,
+ start_line: int,
+ end_line: int,
+ context_lines: int,
+ max_lines: int = _MAX_SOURCE_LINES,
+) -> tuple[str, int, int, int]:
+ """Slice ``text`` to (source, actual_start, actual_end, total_lines).
+
+ Lines are 1-indexed inclusive to match WikiSymbol storage; the range is
+ expanded by ``context_lines`` on both sides and capped at ``max_lines``
+ (truncating from the tail — the head carries the signature, which is what
+ the agent needs to ground itself). The cap is applied AFTER context
+ expansion so the returned span never exceeds it.
+ """
+ lines = text.splitlines()
+ total = len(lines)
+
+ s = max(1, min(start_line, total))
+ e = max(s, min(end_line, total))
+ if context_lines > 0:
+ s = max(1, s - context_lines)
+ e = min(total, e + context_lines)
+
+ if (e - s + 1) > max_lines:
+ e = s + max_lines - 1
+
+ return "\n".join(lines[s - 1 : e]), s, e, total
+
+
+def _number_lines(source: str, start_line: int) -> str:
+ """Prefix each line with its 1-based file line number, Read-style.
+
+ Byte-parity with the agent's own Read tool output (``cat -n`` format:
+ right-aligned number, tab, line). Source served in the exact shape of an
+ already-performed Read is treated as one — the agent edits from it
+ instead of re-Reading the file to "see the real format".
+ """
+ return "\n".join(f"{n:>6}\t{line}" for n, line in enumerate(source.splitlines(), start_line))
+
+
+def _elapsed_ms(t0: float) -> float:
+ return (time.perf_counter() - t0) * 1000
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py b/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py
new file mode 100644
index 000000000..72f277801
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol/tool.py
@@ -0,0 +1,189 @@
+"""MCP Tool: get_symbol — byte-precise source retrieval for a single symbol."""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from repowise.core.persistence.database import get_session
+from repowise.core.registry import mcp_tool_registry as mcp
+
+# Patchable names are read off the package at call time so patches reach them.
+from repowise.server.mcp_server import tool_symbol as _pkg
+from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
+ _get_repo,
+ _unsupported_repo_all,
+)
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._references import (
+ omission_reference,
+)
+from repowise.server.mcp_server._workspace_routing import (
+ hint_misses,
+ needs_routing,
+ other_repo_roots,
+ route_targets,
+)
+
+from .ambiguous import _render_ambiguous
+from .body import _serve_symbol
+from .callees import _MAX_CALLEE_DEPTH
+from .lookup import _resolve_symbol, _rows_in_scope
+from .misses import _not_found_response
+from .omission import _extract_omission_ref, _resolve_omission_ref
+from .ranges import _range_id_read
+from .text import _elapsed_ms
+
+
+def _reference_arguments(
+ reference: dict[str, Any] | None,
+ symbol_id: str | None,
+ id: str | None,
+ repo: str | None,
+) -> tuple[str | None, str | None]:
+ """``symbol_id`` and ``repo`` filled from a structured source reference."""
+ if not reference:
+ return symbol_id, repo
+ if not symbol_id and not id and isinstance(reference.get("id"), str):
+ symbol_id = reference["id"]
+ if repo is None and _pkg._is_workspace_mode() and isinstance(reference.get("repository"), str):
+ repo = reference["repository"]
+ return symbol_id, repo
+
+
+def _requested_id(
+ symbol_id: str | None, id: str | None, query: str | None
+) -> tuple[str | None, str | None]:
+ """The id asked for, from ``symbol_id``, its ``id`` alias, or a lone ``query``."""
+ # Agents call this tool as ``get_symbol(id)``; ``symbol_id`` wins when both are given.
+ if not symbol_id and id:
+ symbol_id = id
+ elif not symbol_id and query and query.strip():
+ # A lone ``query`` is a guessed id: the line filter needs an id to apply to.
+ symbol_id, query = query, None
+ return symbol_id, query
+
+
+async def _routed_read(
+ symbol_id: str, context_lines: int, query: str | None, depth: int
+) -> dict | None:
+ """The read served by the repo that owns *symbol_id*, or None to serve it here."""
+ routes = await route_targets([symbol_id.strip()])
+ if not needs_routing(routes):
+ return None
+ route = routes[0]
+ if route.repo is None:
+ return {"symbol_id": symbol_id, **route.card(), "_meta": _build_meta()}
+ routed = await get_symbol(
+ route.local, context_lines=context_lines, repo=route.repo, query=query, depth=depth
+ )
+ if route.routed:
+ routed = {"repo": route.repo, **routed}
+ hint_misses(routed, routes)
+ return routed
+
+
+async def _indexed_symbol_read(
+ ctx: Any, symbol_id: str, context_lines: int, depth: int, t0: float
+) -> dict:
+ """Resolve *symbol_id* in the index and serve it, its candidates, or a miss."""
+ context_lines = max(0, min(50, context_lines))
+ # Clamped, not rejected: the deepest walk we do is the useful reply.
+ depth = max(1, min(_MAX_CALLEE_DEPTH, depth))
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ rows = await _resolve_symbol(session, repository.id, symbol_id)
+
+ # Before the exclusion spec: it is built from the repo path.
+ if not ctx.path:
+ return {
+ "symbol_id": symbol_id,
+ "error": "MCP server has no repo path configured",
+ "_meta": _build_meta(
+ timing_ms=_elapsed_ms(t0),
+ repository=repository,
+ ),
+ }
+
+ exclude_spec = _get_exclude_spec(ctx.path)
+ rows = await _rows_in_scope(ctx, repository, symbol_id, rows, exclude_spec)
+ if not rows:
+ return await _not_found_response(ctx, repository, symbol_id, exclude_spec, t0)
+ if len(rows) > 1:
+ return await _render_ambiguous(rows, symbol_id, ctx, repository, t0, context_lines)
+ return await _serve_symbol(
+ ctx, repository, rows[0], symbol_id, context_lines, depth, exclude_spec, t0
+ )
+
+
[email protected](surface_order=30, artifact_type="source", presentation="source", evidence_basis="measured")
+async def get_symbol(
+ symbol_id: str | None = None,
+ context_lines: int = 0,
+ repo: str | None = None,
+ query: str | None = None,
+ id: str | None = None,
+ depth: int = 1,
+ reference: dict[str, Any] | None = None,
+) -> dict:
+ """Follow-up read of one symbol whose id another response already gave you.
+
+ **Not an entry point.** ``get_answer`` already ships ``symbol_bodies``, and
+ for a whole file ``get_context(include=["skeleton"])`` or a plain Read is
+ one call instead of many. Reach here for a body that was elided, or for a
+ ``continuation`` / omission ref. Never walk a file symbol by symbol.
+
+ Returns verified, line-numbered source for one indexed symbol, live range,
+ or omission ref. Ambiguity returns every candidate; an index miss returns
+ live fallback lines. A truncated result carries the exact continuation to
+ pass straight back.
+
+ Args:
+ symbol_id: "path/to/file.py::Name", "path/to/file.py:140-180" for a
+ 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. With
+ no id given, it is read as ``symbol_id``.
+ 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``.
+ reference: structured source reference emitted by this tool. Its id
+ and repository are accepted together without caller translation.
+ """
+ symbol_id, repo = _reference_arguments(reference, symbol_id, id, repo)
+ if repo == "all":
+ return _unsupported_repo_all("get_symbol")
+ ctx = await _pkg._resolve_repo_context(repo)
+
+ t0 = time.perf_counter()
+ symbol_id, query = _requested_id(symbol_id, id, query)
+ if not symbol_id or not symbol_id.strip():
+ return {
+ "symbol_id": symbol_id,
+ "error": 'get_symbol requires `symbol_id`, e.g. "path/to/file.py::Name".',
+ "_meta": _build_meta(timing_ms=_elapsed_ms(t0)),
+ }
+
+ omission_ref = _extract_omission_ref(symbol_id)
+ if omission_ref is not None:
+ canonical_omission = omission_reference(symbol_id) or symbol_id
+ return _resolve_omission_ref(
+ canonical_omission,
+ omission_ref,
+ query,
+ ctx.path,
+ t0,
+ other_repo_roots() if repo is None else (),
+ )
+
+ if repo is None:
+ routed = await _routed_read(symbol_id, context_lines, query, depth)
+ if routed is not None:
+ return routed
+ ranged = await _range_id_read(symbol_id, context_lines, ctx, t0)
+ if ranged is not None:
+ return ranged
+ return await _indexed_symbol_read(ctx, symbol_id, context_lines, depth, t0)