Skip to content

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

fix(mcp): verify symbol bounds before serving live slices in get_answer (#796)

Raghav Chamadiya2f052d614f8c
diff --git a/packages/server/src/repowise/server/mcp_server/_verify.py b/packages/server/src/repowise/server/mcp_server/_verify.py
index 0aaa1944f..b17f43c74 100644
--- a/packages/server/src/repowise/server/mcp_server/_verify.py
+++ b/packages/server/src/repowise/server/mcp_server/_verify.py
@@ -188,6 +188,23 @@ def check_symbol_bounds(row: WikiSymbol, source_text: str) -> BoundsCheck:
)
+async def verify_and_heal(session_factory, row: WikiSymbol, source_text: str) -> BoundsCheck:
+ """Run the bounds gate and self-heal a corrected row in one step.
+
+ The shared serve-time contract for every site that turns a stored
+ ``WikiSymbol`` bound into live bytes (get_symbol, the get_answer hydrator,
+ the get_context skeleton): verify against the live file, and when a
+ re-parse moves the bounds, persist the correction so the next serve hits
+ the cheap gate. Healing is best-effort and skipped when no session factory
+ is available (unit tests, index-only contexts) — correctness rides on the
+ returned :class:`BoundsCheck`, not on the write landing.
+ """
+ check = check_symbol_bounds(row, source_text)
+ if check.corrected and session_factory is not None:
+ await heal_symbol_row(session_factory, row, check.start_line, check.end_line)
+ return check
+
+
async def heal_symbol_row(session_factory, row: WikiSymbol, start: int, end: int) -> None:
"""Persist corrected bounds so the next serve hits the cheap gate.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index 66145c326..4bc2e2522 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
@@ -573,8 +573,16 @@ async def get_answer(
homonyms: dict = {"union": {}, "qualified_miss": []}
if question_ids:
with contextlib.suppress(Exception):
+ _anchor_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else None
async with get_session(ctx.session_factory) as session:
- hits, homonyms = await _anchor_symbol_hits(session, repo_id, question_ids, hits)
+ hits, homonyms = await _anchor_symbol_hits(
+ session,
+ repo_id,
+ question_ids,
+ hits,
+ repo_root=_anchor_root,
+ session_factory=ctx.session_factory,
+ )
# Concept anchoring: when a why/value question pins a literal number to a
# described behaviour (no named symbol), grep source COMMENTS for the file
# that justifies the number and anchor it as a dominant hit. Rescues the
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
index 4021d9a61..70f87d81c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
@@ -13,6 +13,7 @@ from typing import Any
from sqlalchemy import select
from repowise.core.persistence.models import WikiSymbol
+from repowise.server.mcp_server._verify import verify_and_heal
from repowise.server.mcp_server.tool_answer.config import (
_ENRICH_TOP_N_HITS,
_HIGH_CONFIDENCE_SCORE_FLOOR,
@@ -66,12 +67,30 @@ def _extract_question_identifiers(question: str) -> set[str]:
return ids
+def _read_repo_text(repo_root: Path | None, file_path: str) -> str | None:
+ """Read a repo file's live text, refusing paths outside the root.
+
+ The single disk read shared by the bounds gate and the signature/body
+ slices below, so a hydrated file is read once rather than once per helper.
+ """
+ if repo_root is None:
+ return None
+ try:
+ abs_path = (repo_root / file_path).resolve()
+ abs_path.relative_to(repo_root.resolve())
+ return abs_path.read_text(encoding="utf-8", errors="replace")
+ except (OSError, ValueError):
+ return None
+
+
def _read_symbol_source(
repo_root: Path | None,
file_path: str,
start_line: int,
end_line: int,
max_lines: int = _MATCHED_SYMBOL_SOURCE_LINES,
+ *,
+ text: str | None = None,
) -> str | None:
"""Return the literal source body for a symbol, bounded to max_lines.
@@ -80,17 +99,16 @@ def _read_symbol_source(
docstring; what it was missing was the actual code. With 40 lines of
the method body in front of it, the synthesis step can answer "how
does X work" without hedging back to "you should inspect the source".
+
+ ``text`` lets a caller that already read the file (the hydrator reads it
+ once for the bounds gate) pass the live source in, so a hydrated file is
+ read once instead of once per symbol.
"""
- if repo_root is None or start_line < 1:
+ if start_line < 1:
return None
- try:
- abs_path = (repo_root / file_path).resolve()
- try:
- abs_path.relative_to(repo_root.resolve())
- except ValueError:
- return None
- text = abs_path.read_text(encoding="utf-8", errors="replace")
- except OSError:
+ if text is None:
+ text = _read_repo_text(repo_root, file_path)
+ if text is None:
return None
lines = text.splitlines()
if start_line > len(lines):
@@ -102,7 +120,7 @@ def _read_symbol_source(
def _read_signature_from_source(
- repo_root: Path | None, file_path: str, start_line: int
+ repo_root: Path | None, file_path: str, start_line: int, *, text: str | None = None
) -> str | None:
"""Read the symbol's actual signature line from disk.
@@ -112,19 +130,12 @@ def _read_signature_from_source(
* decorators (one line above the def)
* full type annotations across line continuations
+ ``text`` reuses the caller's already-read source (see _read_symbol_source).
None on any failure — caller falls back to the stored signature.
"""
- if repo_root is None:
- return None
- try:
- abs_path = (repo_root / file_path).resolve()
- # Defense in depth: never read outside the repo root.
- try:
- abs_path.relative_to(repo_root.resolve())
- except ValueError:
- return None
- text = abs_path.read_text(encoding="utf-8", errors="replace")
- except OSError:
+ if text is None:
+ text = _read_repo_text(repo_root, file_path)
+ if text is None:
return None
lines = text.splitlines()
if not lines or start_line < 1 or start_line > len(lines):
@@ -201,6 +212,8 @@ async def _anchor_symbol_hits(
repo_id: str,
question_ids: set[str],
hits: list[dict],
+ repo_root: Path | None = None,
+ session_factory: Any = None,
) -> tuple[list[dict], dict[str, Any]]:
"""Inject the defining file of a question-named indexed symbol into hits.
@@ -249,6 +262,28 @@ async def _anchor_symbol_hits(
for row in res.scalars().all():
by_name.setdefault(row.name, []).append(row)
+ # Verify bounds against the live file before any body is sliced from a
+ # stored range. Both the answer-by-union bodies (grounding=exact_symbol,
+ # confidence=high) and the anchored tier-0 symbol_bodies serve live source at
+ # these bounds, so a drifted row would otherwise ground the strongest-trust
+ # answer in the wrong lines. Cheap gate first (string check); a re-parse fires
+ # only on a genuine miss and heals the row. One live read per file, cached.
+ _text_cache: dict[str, str | None] = {}
+
+ async def _verified_dict(row) -> dict:
+ d = _symbol_def_dict(row)
+ if row.file_path not in _text_cache:
+ _text_cache[row.file_path] = _read_repo_text(repo_root, row.file_path)
+ text = _text_cache[row.file_path]
+ if text is None:
+ d["_approx"] = True
+ return d
+ check = await verify_and_heal(session_factory, row, text)
+ d["start_line"], d["end_line"] = check.start_line, check.end_line
+ if not check.verified:
+ d["_approx"] = True
+ return d
+
chosen: list = []
for name, cands in by_name.items():
if len(cands) == 1:
@@ -275,13 +310,13 @@ async def _anchor_symbol_hits(
if narrowed:
# Qualifier matched >1 def: union of the narrowed set (still all
# genuine candidates for the qualified name).
- homonyms["union"][name] = [_symbol_def_dict(c) for c in narrowed]
+ homonyms["union"][name] = [await _verified_dict(c) for c in narrowed]
elif targeted:
# Qualifier present but matched nothing: do not guess.
homonyms["qualified_miss"].append(name)
else:
# Bare homonym, no qualifier: union of every def.
- homonyms["union"][name] = [_symbol_def_dict(c) for c in cands]
+ homonyms["union"][name] = [await _verified_dict(c) for c in cands]
if not chosen:
return hits, homonyms
@@ -312,13 +347,18 @@ async def _anchor_symbol_hits(
target["_symbol_anchored"] = True
# Stash the exact symbol the question named so symbol_bodies serves it
# directly — the fuzzy hydration cap drops a far-down method when the
- # parent class name floods every sibling's qualified-name match.
+ # parent class name floods every sibling's qualified-name match. Serve
+ # verified bounds only: an unrelocatable (approximate) symbol still
+ # boosts its file's rank, but is not stashed for a live-body slice.
+ vd = await _verified_dict(sym)
+ if vd.get("_approx"):
+ continue
target.setdefault("_anchor_symbols", []).append(
{
"name": sym.name,
"kind": sym.kind,
- "start_line": sym.start_line,
- "end_line": sym.end_line,
+ "start_line": vd["start_line"],
+ "end_line": vd["end_line"],
}
)
hits.sort(key=lambda h: h.get("score", 0.0), reverse=True)
@@ -362,8 +402,16 @@ def build_homonym_union_bodies(
start = d.get("start_line") or 0
end = d.get("end_line") or 0
symbol_id = f"{path}::{name}"
- body = _read_symbol_source(
- repo_root, path, start, end, max_lines=_HOMONYM_UNION_BODY_MAX_LINES
+ # Bounds that failed live verification (symbol moved and could not be
+ # re-located): don't inline a slice at unreliable lines under a
+ # confidence=high envelope. Hand the agent a get_symbol pointer, which
+ # verifies on its own path.
+ body = (
+ None
+ if d.get("_approx")
+ else _read_symbol_source(
+ repo_root, path, start, end, max_lines=_HOMONYM_UNION_BODY_MAX_LINES
+ )
)
# Budget: always render the first, then only while under budget.
if body and (not symbol_bodies or spent + len(body) <= char_budget):
@@ -540,14 +588,35 @@ async def _hydrate_symbols_for_hits(
)
by_file: dict[str, list[dict]] = {}
repo_root = Path(str(ctx.path)) if ctx and ctx.path else None
+ session_factory = getattr(ctx, "session_factory", None)
+ # One live read per hydrated file, shared by the bounds gate and the
+ # signature/body slices. None when unreadable (missing/outside root).
+ text_cache: dict[str, str | None] = {}
for row in res.scalars().all():
+ if row.file_path not in text_cache:
+ text_cache[row.file_path] = _read_repo_text(repo_root, row.file_path)
+ text = text_cache[row.file_path]
+ # Trust contract (shared with get_symbol): verify the stored bounds
+ # against the live file before slicing a signature or body out of it.
+ # Drift (an edit above the def, or an update lag) otherwise turns into a
+ # garbled signature / body served as if fresh. On a re-parse correction
+ # the row is healed; when the symbol can't be re-located we fall back to
+ # the stored signature and skip the live body — a stored-but-consistent
+ # signature beats a live slice at the wrong lines.
+ if text is not None:
+ check = await verify_and_heal(session_factory, row, text)
+ start_line, end_line, verified = check.start_line, check.end_line, check.verified
+ else:
+ start_line, end_line, verified = row.start_line, row.end_line, False
# Constants/variables: the stored signature IS the verbatim assignment
# line. The disk re-read below walks forward looking for a ":"-closed
# def line and would join unrelated following lines for assignments.
- if row.kind in ("constant", "variable"):
+ if row.kind in ("constant", "variable") or not verified:
rich_sig = None
else:
- rich_sig = _read_signature_from_source(repo_root, row.file_path, row.start_line)
+ rich_sig = _read_signature_from_source(
+ repo_root, row.file_path, start_line, text=text
+ )
# Does the symbol name match any identifier from the question?
name_lower = (row.name or "").lower()
qname_lower = (row.qualified_name or "").lower()
@@ -568,12 +637,14 @@ async def _hydrate_symbols_for_hits(
"kind": row.kind,
"signature": rich_sig or row.signature,
"docstring": row.docstring or "",
- "start_line": row.start_line,
- "end_line": row.end_line,
+ "start_line": start_line,
+ "end_line": end_line,
"_matched": matched,
}
- if matched:
- src = _read_symbol_source(repo_root, row.file_path, row.start_line, row.end_line)
+ if matched and verified:
+ src = _read_symbol_source(
+ repo_root, row.file_path, start_line, end_line, text=text
+ )
if src:
entry["source_excerpt"] = src
by_file.setdefault(row.file_path, []).append(entry)
@@ -624,6 +695,7 @@ async def _hydrate_symbols_for_hits(
s["start_line"],
s.get("end_line") or 0,
max_lines=_SYNTH_FULL_SOURCE_LINES,
+ text=text_cache.get(path),
)
if fuller:
s["source_excerpt"] = fuller
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 574a7bf99..315e8500e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -551,17 +551,31 @@ async def _resolve_skeleton(
}
return
- symbols = [
- SkeletonSymbol(
- name=r.name,
- kind=r.kind,
- start_line=r.start_line,
- end_line=r.end_line,
- signature=r.signature,
- importance=pagerank.get(r.name, 0.0),
+ # Trust contract: the skeleton is sliced on stored bounds but claims
+ # ``verified: True``. Gate each row against the live source first (cheap
+ # string check; a re-parse fires only on a miss) so a drifted bound can't
+ # render the wrong lines as a signature. Corrected rows render at their real
+ # bounds; a symbol that moved and can't be re-located is dropped rather than
+ # garbling the skeleton (its region collapses into an elision marker), which
+ # keeps the ``verified`` claim honest. Healing is left to get_symbol / the
+ # hydrator / incremental update, which hold a writable session on their path.
+ from repowise.server.mcp_server._verify import check_symbol_bounds
+
+ symbols = []
+ for r in rows:
+ check = check_symbol_bounds(r, source)
+ if check.approximate:
+ continue
+ symbols.append(
+ SkeletonSymbol(
+ name=r.name,
+ kind=r.kind,
+ start_line=check.start_line,
+ end_line=check.end_line,
+ signature=r.signature,
+ importance=pagerank.get(r.name, 0.0),
+ )
)
- for r in rows
- ]
result = build_skeleton(
source,
symbols,
diff --git a/tests/unit/server/mcp/test_context_skeleton.py b/tests/unit/server/mcp/test_context_skeleton.py
index 2954d0174..d92aea2d3 100644
--- a/tests/unit/server/mcp/test_context_skeleton.py
+++ b/tests/unit/server/mcp/test_context_skeleton.py
@@ -43,6 +43,54 @@ async def test_skeleton_block_for_file_target(setup_mcp, tmp_path, monkeypatch):
assert "... " in sk["text"] # at least one elision marker
+def _write_drifted_source(tmp_path, rel="src/auth/service.py"):
+ """Same file as ``_write_source`` but shifted down 5 lines.
+
+ The indexed bounds (AuthService 10-100, login 20-40 from conftest) now point
+ into the header filler: synthetic drift. AuthService really sits at line 15,
+ login at 25. A skeleton that trusts the stored bounds would render a filler
+ line as the AuthService "signature" and elide the real ``class`` line.
+ """
+ lines = ["import os", "import sys", "import json", "import re", "import abc"] # 1-5
+ lines += ["# preamble"] * 9 # 6-14
+ lines.append("class AuthService:") # line 15
+ for n in range(16, 25):
+ lines.append(f" setup_{n} = {n}")
+ lines.append(" async def login(self, username: str, password: str) -> Token:") # 25
+ for n in range(26, 46):
+ lines.append(f" step_{n} = {n}")
+ for n in range(46, 106):
+ lines.append(f" tail_{n} = {n}")
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return path
+
+
+async def test_skeleton_verifies_drifted_bounds(setup_mcp, tmp_path, monkeypatch):
+ """``verified: True`` must be honest: drifted symbols are relocated, not garbled.
+
+ Without the bounds gate the skeleton slices signatures at the stored (drifted)
+ lines and would keep a filler line as the AuthService signature while eliding
+ the real ``class`` def, all under a ``verified: True`` claim.
+ """
+ from repowise.server.mcp_server import _state, get_context
+
+ _write_drifted_source(tmp_path)
+ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))
+
+ result = await get_context(["src/auth/service.py"], include=["skeleton"])
+ sk = result["targets"]["src/auth/service.py"]["skeleton"]
+ assert "error" not in sk
+ assert sk["verified"] is True
+ # The real signatures render at their relocated positions. Without the gate
+ # these class/def lines fall inside the drifted "body" region and get elided,
+ # so their presence proves relocation ran.
+ assert "class AuthService:" in sk["text"]
+ assert "async def login" in sk["text"]
+
+
@pytest.mark.asyncio
async def test_skeleton_requires_file_target(setup_mcp, tmp_path, monkeypatch):
from repowise.server.mcp_server import _state, get_context
diff --git a/tests/unit/server/mcp/test_hydrator_bounds_gate.py b/tests/unit/server/mcp/test_hydrator_bounds_gate.py
new file mode 100644
index 000000000..1945f21df
--- /dev/null
+++ b/tests/unit/server/mcp/test_hydrator_bounds_gate.py
@@ -0,0 +1,207 @@
+"""Trust contract: get_answer's hydrator must verify bounds before slicing.
+
+The hydrator turns a stored ``WikiSymbol`` bound into live signature/body bytes
+for ``key_symbols`` and ``symbol_bodies``. Historically it read the live file at
+the stored ``start_line`` with no verification, so a drifted bound (an edit above
+the def, or an index that lagged the working tree) produced a garbled signature
+and a body that started mid-docstring, served as if fresh. These lock the fix:
+the cheap bounds gate runs first, a re-parse relocates and heals a drifted row,
+and an un-relocatable symbol falls back to the stored signature (self-consistent)
+rather than a live slice at the wrong lines.
+
+All deterministic — no LLM, no synthesis. The drift is created synthetically so
+the test does not depend on a naturally stale index.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sqlalchemy import select
+
+from repowise.core.persistence.models import WikiSymbol
+from repowise.server.mcp_server.tool_answer.symbols import _hydrate_symbols_for_hits
+
+# A file whose real ``target_func`` def sits well below the line the index will
+# claim: the stored row points into the import block (the classic post-#779 drift
+# where inserted imports pushed every def down while bounds fossilized).
+_DRIFTED_SOURCE = '''\
+import os
+import sys
+from collections import defaultdict
+from typing import Any
+
+_CONST = 1
+
+
+def target_func(a: int, b: int) -> int:
+ """Add two numbers.
+
+ A short body so the whole thing fits under the slice cap.
+ """
+ total = a + b
+ return total
+'''
+
+_REAL_DEF_LINE = 9 # 1-indexed line of "def target_func"
+_STORED_DRIFT_LINE = 3 # points at "from collections import defaultdict"
+
+
+async def _hydrate_one(session, repo_id, tmp_path, *, session_factory=None):
+ hits = [{"target_path": "mod.py", "page_type": "file_page"}]
+ ctx = SimpleNamespace(path=tmp_path, session_factory=session_factory)
+ await _hydrate_symbols_for_hits(
+ session, repo_id, hits, ctx, question_ids={"target_func"}
+ )
+ return hits[0].get("symbols") or []
+
+
+def _target_row(repo_id, start_line, end_line=15):
+ return WikiSymbol(
+ id="drift1",
+ repository_id=repo_id,
+ file_path="mod.py",
+ symbol_id="mod.py::target_func",
+ name="target_func",
+ qualified_name="mod.target_func",
+ kind="function",
+ signature="def target_func(a, b)",
+ start_line=start_line,
+ end_line=end_line,
+ docstring="Add two numbers.",
+ visibility="public",
+ is_async=False,
+ complexity_estimate=1,
+ language="python",
+ parent_name=None,
+ )
+
+
+async def test_drifted_bounds_are_relocated_not_garbled(session, repo_id, tmp_path):
+ """A stored bound pointing into the import block serves the real def, not junk."""
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ session.add(_target_row(repo_id, start_line=_STORED_DRIFT_LINE))
+ await session.commit()
+
+ syms = await _hydrate_one(session, repo_id, tmp_path)
+ matched = next(s for s in syms if s["name"] == "target_func")
+
+ assert matched["_matched"] is True
+ # Signature is the real def, not the drifted import line it pointed at.
+ assert "def target_func" in matched["signature"]
+ assert "import" not in matched["signature"]
+ # Entry bounds were corrected to the real def location.
+ assert matched["start_line"] == _REAL_DEF_LINE
+ # The body slice starts at the real def, not mid-import.
+ assert matched["source_excerpt"].lstrip().startswith("def target_func")
+
+
+async def test_corrected_row_is_healed(session, factory, repo_id, tmp_path):
+ """When a session factory is available, the drifted row is healed in place."""
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ session.add(_target_row(repo_id, start_line=_STORED_DRIFT_LINE))
+ await session.commit()
+
+ await _hydrate_one(session, repo_id, tmp_path, session_factory=factory)
+
+ # The next serve should hit the cheap gate: the row now carries real bounds.
+ async with factory() as s2:
+ healed = (
+ await s2.execute(select(WikiSymbol).where(WikiSymbol.id == "drift1"))
+ ).scalar_one()
+ assert healed.start_line == _REAL_DEF_LINE
+
+
+async def test_unrelocatable_symbol_falls_back_to_stored_signature(
+ session, repo_id, tmp_path
+):
+ """A symbol the live file no longer defines: serve the stored signature, no body."""
+ # The file defines target_func, but the index row is for a symbol that was
+ # renamed away — relocation cannot find it, so bounds are approximate.
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ row = _target_row(repo_id, start_line=_STORED_DRIFT_LINE)
+ row.name = "renamed_away"
+ row.symbol_id = "mod.py::renamed_away"
+ row.qualified_name = "mod.renamed_away"
+ row.signature = "def renamed_away(a, b)"
+ session.add(row)
+ await session.commit()
+
+ hits = [{"target_path": "mod.py", "page_type": "file_page"}]
+ ctx = SimpleNamespace(path=tmp_path, session_factory=None)
+ await _hydrate_symbols_for_hits(
+ session, repo_id, hits, ctx, question_ids={"renamed_away"}
+ )
+ matched = next(s for s in hits[0]["symbols"] if s["name"] == "renamed_away")
+
+ # Stored signature is served verbatim (self-consistent); no garbled live slice.
+ assert matched["signature"] == "def renamed_away(a, b)"
+ assert "source_excerpt" not in matched
+
+
+async def test_anchor_stashes_verified_bounds_and_heals(
+ session, factory, repo_id, tmp_path
+):
+ """Tier-0 symbol anchoring must stash verified bounds, not the drifted ones."""
+ from repowise.server.mcp_server.tool_answer.symbols import _anchor_symbol_hits
+
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ session.add(_target_row(repo_id, start_line=_STORED_DRIFT_LINE))
+ await session.commit()
+
+ hits: list[dict] = []
+ hits, _homonyms = await _anchor_symbol_hits(
+ session,
+ repo_id,
+ {"target_func"},
+ hits,
+ repo_root=tmp_path,
+ session_factory=factory,
+ )
+ anchored = next(h for h in hits if h.get("_anchor_symbols"))
+ stashed = anchored["_anchor_symbols"][0]
+ assert stashed["name"] == "target_func"
+ assert stashed["start_line"] == _REAL_DEF_LINE # corrected, not the drift line
+
+ async with factory() as s2:
+ healed = (
+ await s2.execute(select(WikiSymbol).where(WikiSymbol.id == "drift1"))
+ ).scalar_one()
+ assert healed.start_line == _REAL_DEF_LINE
+
+
+def test_union_approx_def_routed_to_pointer_not_garbled_body(tmp_path):
+ """An unverifiable union def is handed off as a get_symbol pointer, no slice."""
+ from repowise.server.mcp_server.tool_answer.symbols import build_homonym_union_bodies
+
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ union_groups = {
+ "target_func": [
+ {
+ "file_path": "mod.py",
+ "name": "target_func",
+ "start_line": _STORED_DRIFT_LINE,
+ "end_line": 5,
+ "_approx": True,
+ }
+ ]
+ }
+ bodies, more = build_homonym_union_bodies(tmp_path, union_groups)
+ assert bodies == [] # no live slice served for an unverified bound
+ assert len(more) == 1
+ assert more[0]["symbol_id"] == "mod.py::target_func"
+ assert "get_symbol" in more[0]["hint"]
+
+
+async def test_consistent_bounds_serve_live_without_reparse(session, repo_id, tmp_path):
+ """The happy path: an accurate stored bound serves the live def unchanged."""
+ (tmp_path / "mod.py").write_text(_DRIFTED_SOURCE, encoding="utf-8")
+ session.add(_target_row(repo_id, start_line=_REAL_DEF_LINE))
+ await session.commit()
+
+ syms = await _hydrate_one(session, repo_id, tmp_path)
+ matched = next(s for s in syms if s["name"] == "target_func")
+
+ assert "def target_func" in matched["signature"]
+ assert matched["start_line"] == _REAL_DEF_LINE
+ assert matched["source_excerpt"].lstrip().startswith("def target_func")