Skip to content

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

feat(symbol): outline a large class instead of returning its whole body (#3136)

Raghav Chamadiyab47b6495ead8
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 5a00173ec..e5b196428 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -198,7 +198,7 @@ Returns verified, line-numbered source for one symbol, a live line range, or an
| `query` | string | none | Omission refs only: keep stored lines matching this regex or substring |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
-**Key return fields:** `source` (up to about 600 lines, each prefixed with its line number), start and end lines, `kind`, `truncated` with a continuation to pass back, `ambiguous` and `candidates` when several symbols match, `callee_bodies` (with `depth` above 1), `not_rendered` (bodies past the budget, each with a range read to fetch it), fallback lines from a live grep on a miss.
+**Key return fields:** `source` (up to about 600 lines, each prefixed with its line number), start and end lines, `kind`, `truncated` with a continuation to pass back, `ambiguous` and `candidates` when several symbols match, `callee_bodies` (with `depth` above 1), `not_rendered` (bodies past the budget, each with a range read to fetch it), fallback lines from a live grep on a miss. A class or other container too large to serve whole returns `outlined: true`, its header in `source` and `members` (each member's `symbol_id`, signature and lines, with `members_total` when the list is capped) in place of the body, and no `_meta.complete`.
```
get_symbol(symbol_id="src/auth/service.py::login", depth=2)
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index 977e211b3..3fe4fbbbc 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -375,6 +375,7 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"verified",
"continuation",
"continuation_reference",
+ "members",
"error",
),
),
diff --git a/packages/server/src/repowise/server/mcp_server/_verify.py b/packages/server/src/repowise/server/mcp_server/_verify.py
index 033b6bcd3..8b6218f31 100644
--- a/packages/server/src/repowise/server/mcp_server/_verify.py
+++ b/packages/server/src/repowise/server/mcp_server/_verify.py
@@ -31,8 +31,10 @@ Verification is two-tier:
from __future__ import annotations
import logging
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
+from typing import Any
from repowise.core.persistence.models import WikiSymbol
@@ -104,12 +106,8 @@ def end_anchor_holds(lines: list[str], start_line: int, end_line: int) -> bool:
return _line_indent(after) <= def_indent
-def relocate_symbol(row: WikiSymbol, source_text: str) -> tuple[int, int] | None:
- """Re-parse the live file and find the symbol's current bounds.
-
- Returns (start_line, end_line) or None when the symbol no longer
- exists in the file (deleted/renamed) or the file cannot be parsed.
- """
+def parse_live_symbols(row: WikiSymbol, source_text: str) -> list[Any] | None:
+ """Parse the live file that holds *row*; None when it cannot be parsed."""
try:
from repowise.core.ingestion.models import FileInfo
from repowise.core.ingestion.parser import ASTParser
@@ -130,10 +128,27 @@ def relocate_symbol(row: WikiSymbol, source_text: str) -> tuple[int, int] | None
except Exception as exc:
_log.warning("re-parse failed for %s: %s", row.file_path, exc)
return None
+ return list(parsed.symbols or [])
+
+
+def relocate_symbol(
+ row: WikiSymbol,
+ source_text: str,
+ parsed: Callable[[], list[Any] | None] | None = None,
+) -> tuple[int, int] | None:
+ """Re-parse the live file and find the symbol's current bounds.
+
+ Returns (start_line, end_line) or None when the symbol no longer
+ exists in the file (deleted/renamed) or the file cannot be parsed.
+ ``parsed`` lets a caller checking many rows of one file parse it once.
+ """
+ live = parsed() if parsed is not None else parse_live_symbols(row, source_text)
+ if live is None:
+ return None
# An overload set is several rows under one id; the implementation (the
# one non-declaration) goes first so a stub never answers for it.
- symbols = sorted(parsed.symbols or [], key=lambda sym: sym.is_declaration)
+ symbols = sorted(live, key=lambda sym: sym.is_declaration)
# Strongest match first: exact symbol_id, then (name, parent), then name.
for sym in symbols:
if sym.id == row.symbol_id:
@@ -147,7 +162,11 @@ def relocate_symbol(row: WikiSymbol, source_text: str) -> tuple[int, int] | None
return None
-def check_symbol_bounds(row: WikiSymbol, source_text: str) -> BoundsCheck:
+def check_symbol_bounds(
+ row: WikiSymbol,
+ source_text: str,
+ parsed: Callable[[], list[Any] | None] | None = None,
+) -> BoundsCheck:
"""Verify (and if needed correct) a symbol's bounds against live source.
Cheap gate (no re-parse) only when ALL hold: the name is long enough for
@@ -166,7 +185,7 @@ def check_symbol_bounds(row: WikiSymbol, source_text: str) -> BoundsCheck:
end = min(max(row.end_line, row.start_line), len(lines))
return BoundsCheck(start_line=row.start_line, end_line=end, verified=True)
- located = relocate_symbol(row, source_text)
+ located = relocate_symbol(row, source_text, parsed)
if located is not None:
corrected = located != (row.start_line, row.end_line)
if corrected:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index e9a11bc45..9e67704dc 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -42,6 +42,8 @@ Returns a flat dict (not wrapped in `targets`) so the agent can pipe the
from __future__ import annotations
+import functools
+import json
import re
import sqlite3
import time
@@ -55,6 +57,7 @@ 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,
@@ -82,7 +85,11 @@ from repowise.server.mcp_server._symbol_lookup import (
resolve_symbol_rows,
symbol_id_variants,
)
-from repowise.server.mcp_server._verify import check_symbol_bounds, heal_symbol_row
+from repowise.server.mcp_server._verify import (
+ check_symbol_bounds,
+ heal_symbol_row,
+ parse_live_symbols,
+)
_log = __import__("logging").getLogger("repowise.mcp.symbol")
@@ -95,6 +102,18 @@ _log = __import__("logging").getLogger("repowise.mcp.symbol")
# 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 —
@@ -766,6 +785,73 @@ def _number_lines(source: str, start_line: int) -> str:
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_symbol_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,
@@ -1115,11 +1201,37 @@ async def get_symbol(
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)
+ 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 = None
+ if row.kind in _CONTAINER_KINDS and check.verified:
+ # 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:
+ outline = await _container_outline(
+ ctx.session_factory, repository.id, row, text, check.start_line, check.end_line
+ )
+ if outline is not 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
+ numbered = _number_lines(source, start)
+ truncated = False
+
response = {
"symbol_id": symbol_identity(row.symbol_id),
"file": row.file_path,
@@ -1132,7 +1244,7 @@ async def get_symbol(
"end_line": end,
"symbol_start_line": check.start_line,
"symbol_end_line": check.end_line,
- "source": _number_lines(source, start),
+ "source": numbered,
"truncated": truncated,
"verified": check.verified,
"_meta": _build_meta(
@@ -1143,7 +1255,24 @@ async def get_symbol(
targets=[row.file_path],
),
}
- if not truncated and check.verified:
+ if outline is not None:
+ # 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}."
+ )
+ elif not 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)
@@ -1175,7 +1304,8 @@ async def get_symbol(
"the indexed line range from the current file contents; verify "
"before citing."
)
- if depth > 1:
+ # An outline answers for the shape; callee bodies would undo its size.
+ if depth > 1 and outline is None:
async with get_session(ctx.session_factory) as session:
callee_block = await _expand_callees(
session,
diff --git a/tests/unit/server/mcp/test_symbol_class_outline.py b/tests/unit/server/mcp/test_symbol_class_outline.py
new file mode 100644
index 000000000..a7c06c236
--- /dev/null
+++ b/tests/unit/server/mcp/test_symbol_class_outline.py
@@ -0,0 +1,312 @@
+"""A large class is served as an outline of its members, not its whole body."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from repowise.server.mcp_server import tool_symbol
+
+_METHODS = 30
+_METHOD_BODY = 14
+
+
+def _big_class(
+ offset: int = 0, methods: int = _METHODS
+) -> tuple[str, list[tuple[str, int, int]]]:
+ """Source of a class too large to serve whole, plus each method's bounds.
+
+ ``Big`` ends with a nested ``Inner``; ``Outer`` later in the file holds a
+ second, nested ``Big`` whose members share the parent name.
+ """
+ lines = [""] * offset + ["class Big:", ' """Holds many methods."""', ""]
+ spans: list[tuple[str, int, int]] = []
+ for i in range(methods):
+ start = len(lines) + 1
+ lines.append(f" def method_{i:03d}(self, value: int) -> int:")
+ lines.append(f' """Return value shifted by {i}."""')
+ lines.extend(
+ f" value = value + {i} * {j} # a line of ordinary body text"
+ for j in range(_METHOD_BODY)
+ )
+ lines.append(" return value")
+ spans.append((f"method_{i:03d}", start, len(lines)))
+ lines.append("")
+ lines.extend([" class Inner:", " def deep(self):", " return 2", "", ""])
+ lines.append("def big_function(value):")
+ lines.extend(f" value = value + {j} # filler to make the function large" for j in range(400))
+ lines.extend([" return value", ""])
+ lines.extend(["class Small:", " def one(self):", " return 1", ""])
+ lines.extend(["class Outer:", " class Big:", " def stray(self):", " return 0"])
+ return "\n".join(lines) + "\n", spans
+
+
+def _line(source: str, needle: str) -> int:
+ return next(i for i, ln in enumerate(source.splitlines(), 1) if ln.startswith(needle))
+
+
+def big_repo(tmp_path, monkeypatch):
+ import repowise.server.mcp_server as mcp_mod
+
+ (tmp_path / "pkg").mkdir()
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+ return tmp_path
+
+
+async def _index(session, source: str, spans):
+ """Index *source*'s symbols; returns ``add`` for extra rows."""
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository, WikiSymbol
+
+ repo = (await session.execute(select(Repository))).scalars().first()
+
+ def add(sid, name, kind, sig, start, end, parent=None, doc=None):
+ session.add(
+ WikiSymbol(
+ repository_id=repo.id,
+ file_path="pkg/big.py",
+ symbol_id=sid if ".py::" in sid else f"pkg/big.py::{sid}",
+ name=name,
+ qualified_name=f"pkg.big.{name}",
+ kind=kind,
+ signature=sig,
+ start_line=start,
+ end_line=end,
+ docstring=doc,
+ language="python",
+ parent_name=parent,
+ )
+ )
+
+ inner = _line(source, " class Inner")
+ fn_start = _line(source, "def big_function")
+ small = _line(source, "class Small")
+ outer = _line(source, "class Outer")
+ add("Big", "Big", "class", "class Big", _line(source, "class Big"), inner + 2, doc="Holds many methods.")
+ for name, start, end in spans:
+ add(
+ f"Big::{name}",
+ name,
+ "method",
+ f"def {name}(self, value: int) -> int",
+ start,
+ end,
+ parent="Big",
+ doc=f"Return value shifted by {name[-3:]}.",
+ )
+ add("Big::Inner", "Inner", "class", "class Inner", inner, inner + 2, parent="Big")
+ add("Big::Inner::deep", "deep", "method", "def deep(self)", inner + 1, inner + 2, parent="Inner")
+ add("big_function", "big_function", "function", "def big_function(value)", fn_start, small - 2)
+ add("Small", "Small", "class", "class Small", small, small + 2)
+ add("Small::one", "one", "method", "def one(self)", small + 1, small + 2, parent="Small")
+ add("Outer", "Outer", "class", "class Outer", outer, outer + 3)
+ add("Outer::Big", "Big", "class", "class Big", outer + 1, outer + 3, parent="Outer")
+ add("Outer::Big::stray", "stray", "method", "def stray(self)", outer + 2, outer + 3, parent="Big")
+ await session.flush()
+ return add
+
+
+async def _setup(big_repo, session, **kwargs):
+ source, spans = _big_class(**kwargs)
+ (big_repo / "pkg" / "big.py").write_text(source)
+ add = await _index(session, source, spans)
+ return source, spans, add
+
+
+async def test_large_class_is_outlined_with_member_ids(setup_mcp, big_repo, session):
+ from repowise.server.mcp_server import get_symbol
+
+ source, spans, _ = await _setup(big_repo, session)
+ big_end = _line(source, " class Inner") + 2
+
+ result = await get_symbol("pkg/big.py::Big")
+
+ assert result["outlined"] is True
+ assert result["truncated"] is False
+ assert "complete" not in result["_meta"]
+ assert "members_total" not in result
+ # Header only: declaration and docstring, no method bodies.
+ assert "class Big:" in result["source"]
+ assert "Holds many methods." in result["source"]
+ assert "value = value" not in result["source"]
+ assert (result["symbol_start_line"], result["symbol_end_line"]) == (1, big_end)
+
+ members = result["members"]
+ assert len(members) == _METHODS + 1
+ first = members[0]
+ assert first["symbol_id"] == "pkg/big.py::Big::method_000"
+ assert (first["start_line"], first["end_line"]) == spans[0][1:]
+ assert first["signature"] == "def method_000(self, value: int) -> int"
+ assert first["summary"] == "Return value shifted by 000."
+ assert result["note"].startswith(f"Body (1-{big_end}) outlined")
+ assert f"lines 1-{big_end}" in result["note"]
+ assert len(str(result)) < len(source) // 2
+
+ # The member id is ready for a follow-up call that serves its whole body.
+ method = await get_symbol(first["symbol_id"])
+ assert "outlined" not in method
+ assert "return value" in method["source"]
+ assert method["_meta"]["complete"]
+
+
+async def test_nested_and_unverified_members_stay_in_their_own_class(
+ setup_mcp, big_repo, session
+):
+ from repowise.server.mcp_server import get_symbol
+
+ source, _spans, add = await _setup(big_repo, session)
+ outer = _line(source, "class Outer")
+ # Neither name is in the live file, so both stay unverified; only the one
+ # indexed inside this Big belongs to it.
+ add("Big::ghost_inside", "ghost_inside", "method", "def ghost_inside(self)", 4, 5, parent="Big")
+ add(
+ "Outer::Big::ghost_outside",
+ "ghost_outside",
+ "method",
+ "def ghost_outside(self)",
+ outer + 2,
+ outer + 3,
+ parent="Big",
+ )
+ await session.flush()
+
+ result = await get_symbol("pkg/big.py::Big")
+
+ by_id = {m["symbol_id"]: m for m in result["members"]}
+ assert by_id["pkg/big.py::Big::Inner"]["kind"] == "class"
+ assert by_id["pkg/big.py::Big::ghost_inside"]["bounds"] == "approximate"
+ assert "pkg/big.py::Big::Inner::deep" not in by_id
+ assert "pkg/big.py::Outer::Big::stray" not in by_id
+ assert "pkg/big.py::Outer::Big::ghost_outside" not in by_id
+
+
+async def test_overload_rows_sharing_an_id_are_listed_once(setup_mcp, big_repo, session):
+ from repowise.server.mcp_server import get_symbol
+
+ _source, spans, add = await _setup(big_repo, session)
+ _name, start, end = spans[0]
+ add("./pkg/big.py::Big::method_000", "method_000", "method", "def method_000(self)", start, end, parent="Big")
+ await session.flush()
+
+ result = await get_symbol("pkg/big.py::Big")
+
+ ids = [m["symbol_id"] for m in result["members"]]
+ assert ids.count("pkg/big.py::Big::method_000") == 1
+ assert len(ids) == len(set(ids)) == _METHODS + 1
+
+
+async def test_drifted_members_are_relocated_with_one_parse(
+ setup_mcp, big_repo, session, monkeypatch
+):
+ from repowise.server.mcp_server import get_symbol
+
+ stale_source, spans = _big_class()
+ await _index(session, stale_source, spans)
+ live_source, live_spans = _big_class(offset=5)
+ (big_repo / "pkg" / "big.py").write_text(live_source)
+
+ calls = []
+ real = tool_symbol.parse_live_symbols
+
+ def counting(row, text):
+ calls.append(row.symbol_id)
+ return real(row, text)
+
+ monkeypatch.setattr(tool_symbol, "parse_live_symbols", counting)
+ result = await get_symbol("pkg/big.py::Big")
+
+ assert result["outlined"] is True
+ methods = [m for m in result["members"] if m["kind"] == "method"]
+ assert [(m["start_line"], m["end_line"]) for m in methods] == [s[1:] for s in live_spans]
+ assert len(calls) == 1
+
+
+async def test_small_class_and_function_keep_full_source(setup_mcp, big_repo, session):
+ from repowise.server.mcp_server import get_symbol
+
+ await _setup(big_repo, session)
+
+ small = await get_symbol("pkg/big.py::Small")
+ assert "outlined" not in small
+ assert "return 1" in small["source"]
+ assert small["_meta"]["complete"]
+
+ # A function past the outline size still serves its body, as before.
+ function = await get_symbol("pkg/big.py::big_function")
+ assert "outlined" not in function
+ assert "members" not in function
+ assert "return value" in function["source"]
+ assert len(function["source"]) > tool_symbol._OUTLINE_MIN_CHARS
+
+
+async def test_very_large_class_caps_members_under_the_budget(setup_mcp, big_repo, session):
+ from repowise.server.mcp_server import get_symbol, tool_middleware
+ from repowise.server.mcp_server._budget.contracts import DEFAULT_RESPONSE_CHARS
+
+ await _setup(big_repo, session, methods=250)
+
+ result = await tool_middleware(get_symbol)(symbol_id="pkg/big.py::Big")
+
+ assert "error" not in result
+ assert result["outlined"] is True
+ assert result["members_total"] == 251
+ listed = len(result["members"])
+ assert 0 < listed < 251
+ assert f"{251 - listed} more members are not listed" in result["note"]
+ assert f"after line {result['members'][-1]['end_line']}" in result["note"]
+ assert len(json.dumps(result)) <= DEFAULT_RESPONSE_CHARS
+
+
+async def test_outline_skips_callee_bodies(setup_mcp, big_repo, session, monkeypatch):
+ from repowise.server.mcp_server import get_symbol
+
+ await _setup(big_repo, session)
+
+ async def no_walk(*_args, **_kwargs):
+ raise AssertionError("an outline must not expand callees")
+
+ monkeypatch.setattr(tool_symbol, "_expand_callees", no_walk)
+ result = await get_symbol("pkg/big.py::Big", depth=2)
+
+ assert result["outlined"] is True
+ assert "callee_bodies" not in result
+
+
+async def test_context_lines_never_tip_a_class_into_an_outline(
+ setup_mcp, big_repo, session, monkeypatch
+):
+ from repowise.server.mcp_server import get_symbol
+
+ await _setup(big_repo, session)
+ bare = await get_symbol("pkg/big.py::Small")
+ monkeypatch.setattr(tool_symbol, "_OUTLINE_MIN_CHARS", len(bare["source"]))
+
+ widened = await get_symbol("pkg/big.py::Small", context_lines=20)
+
+ assert len(widened["source"]) > len(bare["source"])
+ assert "outlined" not in widened
+
+
+async def test_context_lines_widen_the_outline_header_upward(setup_mcp, big_repo, session):
+ from repowise.server.mcp_server import get_symbol
+
+ await _setup(big_repo, session, offset=5)
+
+ result = await get_symbol("pkg/big.py::Big", context_lines=3)
+
+ assert result["outlined"] is True
+ assert result["start_line"] == 3
+ assert result["symbol_start_line"] == 6
+ assert "value = value" not in result["source"]