Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
"""Serve-time bounds verification for get_symbol (the trust contract).
WikiSymbol line bounds are written at index time; the file may have changed
since. These tests cover the two-tier check: cheap name-on-line gate, then
one-file re-parse with bound correction, then the approximate fallback.
"""
from __future__ import annotations
import pytest
from repowise.core.persistence.models import WikiSymbol, _new_uuid
from repowise.server.mcp_server._verify import (
check_symbol_bounds,
end_anchor_holds,
heal_symbol_row,
name_at_line,
relocate_symbol,
)
FRESH_SOURCE = '''"""Module."""
def alpha(x):
return x + 1
class Service:
def handle(self, req):
return req
'''
# alpha's body grew by two lines but its definition line is unchanged — the
# stored end (5) now truncates the body (real end is 7). The start gate alone
# would pass and serve a short slice marked verified.
GROWN_SOURCE = '''"""Module."""
def alpha(x):
y = x + 1
z = y + 1
return z
class Service:
def handle(self, req):
return req
'''
# Same file with 4 lines inserted above alpha — every stored bound is stale.
SHIFTED_SOURCE = '''"""Module."""
import os
import sys
NEW_CONSTANT = 7
def alpha(x):
return x + 1
class Service:
def handle(self, req):
return req
'''
def _row(**overrides) -> WikiSymbol:
defaults = dict(
id=_new_uuid(),
repository_id="repo-1",
file_path="pkg/mod.py",
symbol_id="pkg/mod.py::alpha",
name="alpha",
qualified_name="pkg.mod.alpha",
kind="function",
signature="def alpha(x)",
start_line=4,
end_line=5,
language="python",
)
defaults.update(overrides)
return WikiSymbol(**defaults)
class TestNameAtLine:
def test_name_on_stored_line_passes(self) -> None:
assert name_at_line(FRESH_SOURCE.splitlines(), "alpha", 4)
def test_moved_definition_fails(self) -> None:
assert not name_at_line(SHIFTED_SOURCE.splitlines(), "alpha", 4)
def test_out_of_range_line_fails(self) -> None:
assert not name_at_line(FRESH_SOURCE.splitlines(), "alpha", 999)
def test_qualified_name_uses_bare_segment(self) -> None:
assert name_at_line(FRESH_SOURCE.splitlines(), "Service::handle", 9)
def test_annotation_block_is_read_past(self) -> None:
java = [
" @Deprecated",
" @InlineMe(",
' replacement = "this.other()",',
' imports = "a.B")',
" public Builder setLenient() {",
]
assert name_at_line(java, "setLenient", 1)
assert name_at_line(["#[test]", "fn parses() {}"], "parses", 1)
assert name_at_line(["LRESULT", "Window::MessageHandler(HWND h) {"], "MessageHandler", 1)
# Code above the definition is not an annotation, so a shift still fails.
assert not name_at_line([" int x = 1;", " @Override", " void run() {"], "run", 1)
def test_an_annotation_argument_does_not_define_the_name(self) -> None:
assert not name_at_line(['@Deprecated(since="foo")', "void bar() {"], "foo", 1)
assert name_at_line(['@Deprecated(since="foo")', "void foo() {"], "foo", 1)
assert name_at_line(["@cache", "def foo():"], "foo", 1)
# One line holding the annotation and the definition still passes.
assert name_at_line(["@Test fun parsesInput() {"], "parsesInput", 1)
assert not name_at_line(['@Named("parsesInput")', "fun other() {"], "parsesInput", 1)
@pytest.mark.parametrize(
"head",
["pass", "return", "x", "int x"],
)
def test_a_statement_line_is_not_a_type_head(self, head: str) -> None:
# A shift that lands one line above a definition must still fail.
assert not name_at_line([head, "def foo_bar():"], "foo_bar", 1)
assert not name_at_line([head, " foo_bar()"], "foo_bar", 1)
def test_type_heads_read_past_at_most_two_lines(self) -> None:
cpp = ["template <typename T>", "static int", "Grow(T x) {"]
assert name_at_line(cpp, "Grow", 1)
assert not name_at_line(["LRESULT", "LRESULT", "LRESULT", "Run() {"], "Run", 1)
class TestCheckSymbolBounds:
def test_fresh_bounds_verified_without_reparse(self) -> None:
check = check_symbol_bounds(_row(), FRESH_SOURCE)
assert check.verified
assert not check.corrected
assert (check.start_line, check.end_line) == (4, 5)
def test_stale_bounds_corrected_via_reparse(self) -> None:
check = check_symbol_bounds(_row(), SHIFTED_SOURCE)
assert check.verified
assert check.corrected
# alpha moved from line 4 to line 10 in the shifted source.
assert check.start_line == 10
slice_lines = SHIFTED_SOURCE.splitlines()[check.start_line - 1 : check.end_line]
assert "def alpha(x):" in slice_lines[0]
def test_deleted_symbol_is_approximate(self) -> None:
row = _row(name="ghost", symbol_id="pkg/mod.py::ghost", qualified_name="ghost")
check = check_symbol_bounds(row, SHIFTED_SOURCE)
assert not check.verified
assert check.approximate
def test_method_relocated_by_name_and_parent(self) -> None:
row = _row(
name="handle",
symbol_id="pkg/mod.py::Service::handle",
qualified_name="Service::handle",
kind="method",
parent_name="Service",
start_line=9,
end_line=10,
)
check = check_symbol_bounds(row, SHIFTED_SOURCE)
assert check.verified
assert check.corrected
assert "def handle" in SHIFTED_SOURCE.splitlines()[check.start_line - 1]
def test_interior_body_growth_forces_correction(self) -> None:
# Definition line unchanged, but the body grew — the start gate passes
# yet the stored end (5) truncates the symbol. The end anchor must
# catch it and re-parse to the true end (7), not serve a short slice.
check = check_symbol_bounds(_row(), GROWN_SOURCE)
assert check.verified
assert check.corrected
assert (check.start_line, check.end_line) == (4, 7)
def test_short_name_skips_cheap_gate(self) -> None:
# "db" is a substring of "dbquery()" but isn't this symbol. A 1-2 char
# name must not be rubber-stamped by substring containment; with no
# real symbol to relocate, the result is approximate, not verified.
src = "result = self.dbquery()\n"
row = _row(
name="db", symbol_id="pkg/mod.py::db", qualified_name="db", start_line=1, end_line=1
)
check = check_symbol_bounds(row, src)
assert not check.verified
assert check.approximate
class TestEndAnchor:
def test_eof_after_symbol_holds(self) -> None:
assert end_anchor_holds(FRESH_SOURCE.splitlines(), 8, 10)
def test_blank_line_after_symbol_holds(self) -> None:
assert end_anchor_holds(FRESH_SOURCE.splitlines(), 4, 5)
def test_deeper_indent_after_stored_end_fails(self) -> None:
# Line 6 (" z = y + 1") is still body — stored end of 5 is wrong.
assert not end_anchor_holds(GROWN_SOURCE.splitlines(), 4, 5)
def test_out_of_range_end_fails(self) -> None:
assert not end_anchor_holds(FRESH_SOURCE.splitlines(), 4, 0)
class TestRelocateSymbol:
def test_relocate_finds_exact_symbol_id(self) -> None:
located = relocate_symbol(_row(), SHIFTED_SOURCE)
assert located is not None
assert located[0] == 10
def test_relocate_serves_the_implementation_not_an_overload_stub(self) -> None:
source = (
"from typing import overload\n"
"\n"
"\n"
"@overload\n"
"def alpha(x: int) -> int: ...\n"
"@overload\n"
"def alpha(x: str) -> str: ...\n"
"def alpha(x):\n"
" return x\n"
)
assert relocate_symbol(_row(), source) == (8, 9)
def test_relocate_returns_none_for_missing_symbol(self) -> None:
row = _row(name="ghost", symbol_id="pkg/mod.py::ghost")
assert relocate_symbol(row, SHIFTED_SOURCE) is None
def test_relocate_handles_unparseable_language(self) -> None:
row = _row(language="no-such-language")
assert relocate_symbol(row, SHIFTED_SOURCE) is None
@pytest.mark.asyncio
async def test_heal_symbol_row_persists_corrected_bounds(setup_mcp, factory, session):
from sqlalchemy import select
from repowise.core.persistence.models import Repository
repo = (await session.execute(select(Repository))).scalars().first()
row = _row(repository_id=repo.id)
session.add(row)
await session.commit()
await heal_symbol_row(factory, row, 42, 57)
from repowise.core.persistence.database import get_session
async with get_session(factory) as s:
healed = (await s.execute(select(WikiSymbol).where(WikiSymbol.id == row.id))).scalar_one()
assert (healed.start_line, healed.end_line) == (42, 57)
class TestUnverifiedBoundsAreStillClampedToTheLiveFile:
"""D8: an unverified end that overshoots EOF made a whole body look cut.
The cheap gate clamps (``min(..., len(lines))``) and a re-parse returns real
bounds, so this was the one return handing back a raw stored end. Everything
downstream inherited it: get_answer's hydrator computes ``truncated`` from
it, and get_symbol / get_context slice with it.
"""
def test_an_unrelocatable_symbol_does_not_report_an_end_past_eof(self) -> None:
# A name that is nowhere in the source, so both the cheap gate and the
# re-parse relocation fail and the approximate branch is taken.
row = _row(name="vanished", symbol_id="pkg/mod.py::vanished", end_line=900)
check = check_symbol_bounds(row, FRESH_SOURCE)
assert check.verified is False
assert check.approximate is True
assert check.end_line == len(FRESH_SOURCE.splitlines())
def test_an_unverified_end_inside_the_file_is_left_alone(self) -> None:
"""The control: clamping must not shorten a bound that already fits."""
row = _row(name="vanished", symbol_id="pkg/mod.py::vanished", end_line=6)
check = check_symbol_bounds(row, FRESH_SOURCE)
assert check.verified is False
assert check.end_line == 6