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): check caller definition lines live and fold plurals in symbol search (#3741)

Swati Ahuja2d98acfd0837
diff --git a/packages/server/src/repowise/server/mcp_server/_edit_sites.py b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
index 3700eed03..3cc445858 100644
--- a/packages/server/src/repowise/server/mcp_server/_edit_sites.py
+++ b/packages/server/src/repowise/server/mcp_server/_edit_sites.py
@@ -15,6 +15,7 @@ import json
import os
import re
from collections import Counter
+from collections.abc import Iterable
from itertools import islice
from pathlib import Path, PurePosixPath
from typing import Any
@@ -30,7 +31,7 @@ from repowise.core.test_paths import is_test_related_path
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
from repowise.server.mcp_server._helpers import read_repo_file_text
from repowise.server.mcp_server._meta import _working_tree_dirty_paths, uncommitted_targets
-from repowise.server.mcp_server._verify import relocate_symbol
+from repowise.server.mcp_server._verify import _MIN_GATE_NAME_LEN, name_at_line, relocate_symbol
MAX_SITES = 200
MAX_TEXT_CHARS = 160
@@ -74,6 +75,20 @@ _CALL_AFTER = re.compile(r"\s*(?:\?\.)?\(")
# ``new name`` and a JSX tag.
_LOCAL_USE_AFTER = re.compile(r"\s*(?:\(|\?\.|\.(?!\.))")
_LOCAL_USE_BEFORE = re.compile(r"(?:\bnew\s+|</?)$")
+# The call forms of the indexed languages, so a line that only mentions a
+# callee (prose, a field, a type) is not served as its call. Brackets or type
+# arguments after it (``f(``, ``f?.(``, ``f!(``, ``f[``, ``f {``, ``f<T>(``), a
+# reference, decorator or Lisp form before it (``T::f``, ``@f``, ``(f``), or a
+# bracketless command call at the head of an expression (``run "$x"``).
+_CALL_FORM_AFTER = re.compile(r"\s*(?:\?\.|[?!])?\s*[(\[{]|(?:::)?<")
+_CALL_FORM_BEFORE = re.compile(r"(?:::|[@(])$")
+# Ceiling: a bracketless call on a receiver (Ruby ``obj.foo arg``) is not read
+# as a call, so its call line is dropped; widen here if that gap shows up.
+_COMMAND_HEAD = re.compile(
+ r"(?:^|[=;&|,>!`]|\$\(|\b(?:if|then|do|else|elif|while|until|return|exec|perform))\s*$",
+ re.IGNORECASE,
+)
+_COMMAND_ARGS = re.compile(r"\s+[^\s=:;,.)\]}|&<>+*/%-]|\s*[;.]?\s*$")
def _bare_name(node: GraphNode) -> str:
@@ -155,58 +170,110 @@ def _renames(
return aliases, aliases & imported
+def _calls(text: str, name: str) -> bool:
+ """Whether *text* uses *name* in one of the call forms above."""
+ return any(
+ _CALL_FORM_AFTER.match(text, m.end())
+ or _CALL_FORM_BEFORE.search(text, 0, m.start())
+ or _LOCAL_USE_BEFORE.search(text, 0, m.start())
+ or (_COMMAND_HEAD.search(text, 0, m.start()) and _COMMAND_ARGS.match(text, m.end()))
+ for m in _word(name).finditer(text)
+ )
+
+
def _call_texts(
- root: Path, wanted: dict[str, set[tuple[int, str]]]
-) -> dict[tuple[str, int, str], str]:
- """``(file, line, name) -> text`` for each line that still names *name* or its import alias."""
+ root: Path,
+ wanted: dict[str, set[tuple[int, str]]],
+ defs: dict[str, set[tuple[int, str]]],
+) -> tuple[dict[tuple[str, int, str], str], set[tuple[str, int, str]]]:
+ """``(file, line, name) -> text`` for each line that still calls *name* or its
+ import alias, and the *defs* ``(file, line, name)`` whose live line no longer
+ defines *name*. A file that cannot be read answers neither."""
out: dict[tuple[str, int, str], str] = {}
- for rel, asks in wanted.items():
+ moved: set[tuple[str, int, str]] = set()
+ for rel in wanted.keys() | defs.keys():
lines = _read_lines(root, rel)
if lines is None:
continue
+ moved.update(
+ (rel, n, name) for n, name in defs.get(rel, ()) if not name_at_line(lines, name, n)
+ )
imports: set[int] | None = None
- for n, name in asks:
+ for n, name in wanted.get(rel, ()):
if not 0 < n <= len(lines):
continue
text = lines[n - 1]
- if not _word(name).search(text):
+ if not _calls(text, name):
if imports is None:
imports = _import_lines(lines)
python = Path(rel).suffix in _PYTHON_EXTENSIONS
_, local = _renames(lines, name, imports, python)
- if not any(_word(a).search(text) for a in local):
+ if not any(_calls(text, a) for a in local):
continue
out[(rel, n, name)] = text.strip()[:MAX_TEXT_CHARS]
- return out
+ return out, moved
def _leaf(symbol_id: str) -> str:
return id_segment_name(symbol_id.split("::")[-1].split(".")[-1])
+def _row_checks(
+ rows: list[dict[str, Any]], callee_id: str | None
+) -> tuple[dict[int, tuple[str, int, str]], dict[int, tuple[str, int, str]]]:
+ """Per row index, ``(file, call_line, callee)`` and ``(file, line, caller)`` to check live."""
+ asks: dict[int, tuple[str, int, str]] = {}
+ defs: dict[int, tuple[str, int, str]] = {}
+ for i, row in enumerate(rows):
+ if not row.get("file"):
+ continue
+ callee = row.get("via_wrapper") or row.get("target") or callee_id
+ if row.get("call_line") and callee:
+ asks[i] = (row["file"], row["call_line"], _leaf(callee))
+ caller = row.get("symbol_id") or row.get("caller") or ""
+ # A name too short to tell apart on a line is left unchecked, as in get_symbol.
+ name = _leaf(caller) if "::" in caller else ""
+ if row.get("line") and len(name) >= _MIN_GATE_NAME_LEN:
+ defs[i] = (row["file"], row["line"], name)
+ return asks, defs
+
+
+def _by_file(keys: Iterable[tuple[str, int, str]]) -> dict[str, set[tuple[int, str]]]:
+ out: dict[str, set[tuple[int, str]]] = {}
+ for rel, n, name in keys:
+ out.setdefault(rel, set()).add((n, name))
+ return out
+
+
async def attach_call_text(
repo_root: str | Path | None, rows: list[dict[str, Any]], callee_id: str | None = None
) -> None:
- """Add ``text``, the live source at ``call_line``, where that line still names the callee.
+ """Add ``text``, the live source at ``call_line``, where that line still calls the callee.
The callee is the row's ``via_wrapper``, else its ``target``, else
- *callee_id*. A line that no longer names it (the file moved under the
+ *callee_id*. A line that no longer calls it (the file moved under the
index), or a file that cannot be read, loses ``call_line`` too, so no
- stale line is served. One read per distinct file, off the event loop.
+ stale line is served. The caller's definition ``line`` is checked the
+ same way: when the live line no longer defines the caller the row loses
+ ``line`` and ``call_line``. One read per distinct file, off the event loop.
"""
- asks: dict[int, tuple[str, int, str]] = {}
- for i, row in enumerate(rows):
- callee = row.get("via_wrapper") or row.get("target") or callee_id
- if row.get("call_line") and row.get("file") and callee:
- asks[i] = (row["file"], row["call_line"], _leaf(callee))
- if not asks:
+ asks, defs = _row_checks(rows, callee_id)
+ if not asks and not defs:
return
texts: dict[tuple[str, int, str], str] = {}
+ moved: set[tuple[str, int, str]] = set()
if repo_root:
- wanted: dict[str, set[tuple[int, str]]] = {}
- for rel, n, name in asks.values():
- wanted.setdefault(rel, set()).add((n, name))
- texts = await asyncio.to_thread(_call_texts, Path(repo_root).resolve(), wanted)
+ texts, moved = await asyncio.to_thread(
+ _call_texts,
+ Path(repo_root).resolve(),
+ _by_file(asks.values()),
+ _by_file(defs.values()),
+ )
+ for i, key in defs.items():
+ if key in moved:
+ rows[i].pop("line", None)
+ asks.pop(i, None)
+ rows[i].pop("call_line", None)
for i, key in asks.items():
if text := texts.get(key):
rows[i]["text"] = text
diff --git a/packages/server/src/repowise/server/mcp_server/_hit_symbols.py b/packages/server/src/repowise/server/mcp_server/_hit_symbols.py
index fd23f76a2..a1e78a5fb 100644
--- a/packages/server/src/repowise/server/mcp_server/_hit_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/_hit_symbols.py
@@ -25,7 +25,7 @@ from repowise.server.mcp_server._helpers import _get_repo
from repowise.server.mcp_server._meta import served_root
from repowise.server.mcp_server._page_paths import hit_file_path
from repowise.server.mcp_server._query_terms import content_terms
-from repowise.server.mcp_server.tool_search_symbols import _tokens
+from repowise.server.mcp_server.tool_search_symbols import _stem, _tokens
_log = logging.getLogger("repowise.mcp.search")
@@ -41,11 +41,6 @@ _COMMENT_ONLY = re.compile(r"^\s*(?:#|//|/\*|\*|--|<!--)")
_VALUE_KINDS = frozenset({"constant", "variable", "property"})
-def _stem(word: str) -> str:
- """``files`` -> ``file``: enough inflection folding to match prose to names."""
- return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word
-
-
def _stems(text: str | None) -> set[str]:
return {_stem(t) for t in _tokens(text)}
diff --git a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
index 736bb8316..499f76212 100644
--- a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
@@ -56,11 +56,11 @@ from repowise.server.mcp_server._helpers import (
_get_repo,
is_excluded,
)
-from repowise.server.mcp_server._hit_symbols import _stem
from repowise.server.mcp_server._page_paths import PAGELESS_FILE
from repowise.server.mcp_server._query_terms import _MAX_TERMS, STOPWORDS
from repowise.server.mcp_server._query_terms import content_terms as content_terms
from repowise.server.mcp_server.tool_search_symbols import (
+ _stem,
_symbol_kind_for_request_kind,
_symbol_result,
_tokens,
diff --git a/packages/server/src/repowise/server/mcp_server/_verify.py b/packages/server/src/repowise/server/mcp_server/_verify.py
index 8b6218f31..2f0754a10 100644
--- a/packages/server/src/repowise/server/mcp_server/_verify.py
+++ b/packages/server/src/repowise/server/mcp_server/_verify.py
@@ -31,6 +31,7 @@ Verification is two-tier:
from __future__ import annotations
import logging
+import re
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
@@ -46,6 +47,33 @@ _log = logging.getLogger("repowise.mcp.verify")
# confirm them. (Module-level constants/variables now indexed make short
# names common, so the gate must not rubber-stamp them.)
_MIN_GATE_NAME_LEN = 3
+# A line opening an annotation, attribute or decorator, which JVM, Swift, Rust
+# and C# definitions can start on. Lines inside its brackets continue it.
+_ATTRIBUTE_LINE = re.compile(r"^\s*(?:@|#\[|\[)")
+# A C/C++ return-type or template line above the name (``LRESULT``,
+# ``static int``, ``template <typename T>``): one type-like token, at most one
+# qualifier before it. A bare statement keyword is not a type.
+_TYPE_HEAD = re.compile(
+ r"^\s*(?:(?:static|inline|extern|virtual|constexpr|const|unsigned|signed|friend|explicit)\s+)?"
+ r"(template\s*<.*>|[A-Za-z_][\w:]*(?:<.*>)?)[\s*&]*$"
+)
+# Control-flow and statement words: a line led by one is not a definition or
+# its type head.
+NOT_A_DEFINITION = frozenset(
+ {
+ "if", "for", "while", "switch", "catch", "else", "do", "try", "return",
+ "with", "using", "lock", "foreach", "case", "synchronized", "await",
+ "yield", "new", "typeof", "in", "of", "when", "unless", "match",
+ "raise", "throw", "assert", "del", "delete", "print", "elif", "except",
+ "finally", "import", "from", "global", "nonlocal", "pass", "break",
+ "continue", "go", "defer", "select", "range", "constructor",
+ }
+)
+# ``end`` closes a Ruby or Lua block, but it is a real JS method name, so only
+# the type-head check refuses it.
+_NOT_A_TYPE_HEAD = NOT_A_DEFINITION | {"end"}
+_MAX_TYPE_HEAD_LINES = 2
+_MAX_ATTRIBUTE_LINES = 20
@dataclass
@@ -65,12 +93,70 @@ def name_at_line(lines: list[str], name: str, start_line: int) -> bool:
``lines`` is the live file split into lines; ``start_line`` is
1-indexed. The bare name (last segment of a qualified name) must appear
as a substring of the definition line — true for def/class/assignment
- lines across every indexed language.
+ lines across every indexed language. A recorded start on an annotation
+ block (``@Override``, ``#[test]``, ``[Fact]``, one spanning lines) or a
+ return-type line (``LRESULT``) is read past to the line it heads.
"""
if start_line < 1 or start_line > len(lines):
return False
bare = _bare_name(name)
- return bool(bare) and bare in lines[start_line - 1]
+ if not bare:
+ return False
+ depth = heads = 0
+ for text in lines[start_line - 1 : start_line - 1 + _MAX_ATTRIBUTE_LINES]:
+ # An annotation's arguments can name anything (``@Deprecated(since="foo")``),
+ # so only the code after it on the line counts.
+ if depth:
+ depth = _depth_after(depth, text)
+ elif _ATTRIBUTE_LINE.match(text):
+ if bare in _after_attributes(text):
+ return True
+ depth = _depth_after(0, text)
+ elif bare in text:
+ return True
+ elif heads < _MAX_TYPE_HEAD_LINES and _is_type_head(text):
+ heads += 1
+ else:
+ return False
+ return False
+
+
+def _depth_after(depth: int, text: str) -> int:
+ return max(0, depth + sum(map(text.count, "([{")) - sum(map(text.count, ")]}")))
+
+
+def _after_attributes(text: str) -> str:
+ """*text* past its leading annotations (``@A(x) @B [C] #[d]``); empty when one stays open."""
+ i, n = 0, len(text)
+ while True:
+ while i < n and text[i].isspace():
+ i += 1
+ if text.startswith("@", i):
+ i += 1
+ while i < n and (text[i].isalnum() or text[i] in "_.:"):
+ i += 1
+ if not text.startswith("(", i):
+ continue
+ elif text.startswith("#[", i):
+ i += 1
+ elif not text.startswith("[", i):
+ return text[i:]
+ depth = 0
+ for j in range(i, n):
+ depth += (text[j] in "([{") - (text[j] in ")]}")
+ if not depth:
+ i = j + 1
+ break
+ else:
+ return ""
+
+
+def _is_type_head(text: str) -> bool:
+ m = _TYPE_HEAD.match(text)
+ if m is None:
+ return False
+ token = m.group(1)
+ return token.startswith("template") or (len(token) >= 3 and token not in _NOT_A_TYPE_HEAD)
def _bare_name(name: str) -> str:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/withheld.py b/packages/server/src/repowise/server/mcp_server/tool_answer/withheld.py
index f61ed31a3..e24b0e62e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/withheld.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/withheld.py
@@ -10,6 +10,7 @@ import re
from collections.abc import Iterator
from pathlib import Path
+from repowise.server.mcp_server._verify import NOT_A_DEFINITION
from repowise.server.mcp_server.tool_answer.source import (
_read_repo_text,
_read_signature_from_source,
@@ -77,16 +78,7 @@ _BRACE_MEMBER = len(_WITHHELD_DEF_PATTERNS) - 1
# Words that make a brace-member match control flow or a statement rather than
# a definition. Checked against the matched name and the line's first word,
# since the optional type group can swallow the keyword (``raise X(...{``).
-_NOT_A_DEFINITION = frozenset(
- {
- "if", "for", "while", "switch", "catch", "else", "do", "try", "return",
- "with", "using", "lock", "foreach", "case", "synchronized", "await",
- "yield", "new", "typeof", "in", "of", "when", "unless", "match",
- "raise", "throw", "assert", "del", "delete", "print", "elif", "except",
- "finally", "import", "from", "global", "nonlocal", "pass", "break",
- "continue", "go", "defer", "select", "range", "constructor",
- }
-)
+_NOT_A_DEFINITION = NOT_A_DEFINITION
_FIRST_WORD_RE = re.compile(r"[A-Za-z_$][\w$]*")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
index 8c7c30fc4..c40c42126 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
@@ -84,6 +84,29 @@ def _tokens(text: str | None) -> set[str]:
return out
+def _stem(word: str) -> str:
+ """``files`` -> ``file``: enough inflection folding to match prose to names."""
+ return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word
+
+
+def _singulars(word: str) -> set[str]:
+ """*word* and each singular a regular plural of it could come from.
+
+ ``classes`` -> ``{classes, classe, class}``, ``factories`` adds ``factory``.
+ Two words match when their sets overlap, so ``caches`` still meets
+ ``cache`` and ``responses`` meets ``response``, which no single rule for
+ ``-es`` gets right for both. Ceiling: regular English plurals.
+ """
+ out = {word}
+ if len(word) > 3 and word.endswith("s") and not word.endswith("ss"):
+ out.add(word[:-1])
+ if len(word) > 4 and word.endswith("es"):
+ out.add(word[:-2])
+ if len(word) > 4 and word.endswith("ies"):
+ out.add(word[:-3] + "y")
+ return out
+
+
def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], qnorm: str) -> float:
"""Rank a candidate symbol against the query (higher = better).
@@ -94,7 +117,9 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
"""
name = (row.name or "").lower()
qn = _qual_norm(row.qualified_name)
- stoks = _tokens(row.name) | _tokens(row.qualified_name)
+ # Plurals folded on both sides, so ``type`` covers ``declared_types_in``.
+ forms = set().union(*map(_singulars, _tokens(row.name) | _tokens(row.qualified_name)))
+ covered = sum(1 for t in qtokens if _singulars(t) & forms)
score = 0.0
# Exact match on the bare name or the (separator-normalised) qualified name.
@@ -106,9 +131,8 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
score += 40.0
# Token coverage: how much of the query the symbol's tokens account for.
if qtokens:
- matched = qtokens & stoks
- score += 30.0 * (len(matched) / len(qtokens))
- if qtokens <= stoks: # every query token is present
+ score += 30.0 * (covered / len(qtokens))
+ if covered == len(qtokens): # every query token is present
score += 20.0
# Substring fallback for partial identifiers ("index_re").
if qnorm and (qnorm in name or qnorm in qn):
@@ -167,8 +191,17 @@ def _candidate_filter(qtokens: set[str], qnorm: str):
clauses.append(
WikiSymbol.qualified_name.ilike(f"%{escape_like(qnorm)}%", escape=LIKE_ESCAPE)
)
- for tok in qtokens:
- esc = escape_like(tok)
+ # Every singular form, so ``classes`` still finds ``MyClass``, and a ``-y``
+ # word cut to its stem, so ``factory`` still finds ``createFactories``. A
+ # form that contains another adds nothing to a substring match.
+ forms = {
+ f[:-1] if len(f) > 3 and f.endswith("y") else f
+ for f in set().union(*map(_singulars, qtokens))
+ }
+ for form in forms:
+ if any(other != form and other in form for other in forms):
+ continue
+ esc = escape_like(form)
clauses.append(WikiSymbol.name.ilike(f"%{esc}%", escape=LIKE_ESCAPE))
clauses.append(WikiSymbol.qualified_name.ilike(f"%{esc}%", escape=LIKE_ESCAPE))
return or_(*clauses) if clauses else None
diff --git a/tests/unit/server/mcp/test_answer_graph_neighbors.py b/tests/unit/server/mcp/test_answer_graph_neighbors.py
index 4af69b4bf..8bd139ccb 100644
--- a/tests/unit/server/mcp/test_answer_graph_neighbors.py
+++ b/tests/unit/server/mcp/test_answer_graph_neighbors.py
@@ -123,7 +123,8 @@ async def test_ts_lead_file_users_with_kinds(session, populated_db, tmp_path):
]
)
await session.flush()
- _write(tmp_path, "src/handlers.ts", "\n" * 11 + " handleCompactionEnd(ctx);\n")
+ _write(tmp_path, "src/handlers.ts",
+ "\n" * 4 + "export function createHandler() {\n" + "\n" * 6 + " handleCompactionEnd(ctx);\n")
_write(tmp_path, "src/lifecycle.ts",
'export { handleCompactionEnd } from "./compaction.js";\n')
_write(tmp_path, "src/runner.ts",
diff --git a/tests/unit/server/mcp/test_answer_withheld_symbols.py b/tests/unit/server/mcp/test_answer_withheld_symbols.py
index f07f9dcb3..99b0a1991 100644
--- a/tests/unit/server/mcp/test_answer_withheld_symbols.py
+++ b/tests/unit/server/mcp/test_answer_withheld_symbols.py
@@ -940,6 +940,8 @@ def test_the_function_keyword_is_not_matched_as_an_identifier_prefix(line) -> No
("export function useThing(a) {", "useThing"),
("export function* gen() {", "gen"),
("export default async function run() {", "run"),
+ # A JS method named like a Ruby block closer is still a definition.
+ (" end(chunk) {", "end"),
],
)
def test_real_function_declarations_still_match(line, expected) -> None:
diff --git a/tests/unit/server/mcp/test_caller_call_text.py b/tests/unit/server/mcp/test_caller_call_text.py
index 33b76fc4e..bba7143d6 100644
--- a/tests/unit/server/mcp/test_caller_call_text.py
+++ b/tests/unit/server/mcp/test_caller_call_text.py
@@ -205,6 +205,118 @@ async def test_shifted_call_line_is_dropped(
assert "call_line" not in row and "text" not in row
+async def test_a_moved_definition_loses_its_line_and_call_line(session, populated_db, tmp_path):
+ rid = populated_db
+ py = {"language": "python"}
+ # Two lines were added above `tick` since indexing, and the stale call line
+ # now lands on its docstring, which still names the callee.
+ _write(tmp_path, "app/diag.py", ["import os", "", "def tick():",
+ ' """Calls prune_rows once a minute."""', " prune_rows(1)"])
+ session.add_all(
+ [
+ _sym(rid, "lib/poll.py::prune_rows", lines=(10, 40), **py),
+ _sym(rid, "app/diag.py::tick", lines=(1, 3), **py),
+ _edge(rid, "app/diag.py::tick", "lib/poll.py::prune_rows", call_lines=[4]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "lib/poll.py::prune_rows", tmp_path)
+ assert row["name"] == "tick"
+ assert not {"line", "call_line", "text"} & row.keys()
+ ev = await callers.caller_evidence(
+ session, rid, "Who calls prune_rows?", {"prune_rows"}, [], repo_root=tmp_path
+ )
+ (answer_row,) = ev.rows
+ assert not {"line", "call_line", "text"} & answer_row.keys()
+
+
+async def test_a_line_that_only_mentions_the_callee_is_not_its_call(
+ session, populated_db, tmp_path
+):
+ rid = populated_db
+ py = {"language": "python"}
+ _write(tmp_path, "app/diag.py", ["def tick():", ' """Calls prune once a minute."""',
+ " prune(1)"])
+ session.add_all(
+ [
+ _sym(rid, "lib/poll.py::prune", lines=(10, 40), **py),
+ _sym(rid, "app/diag.py::tick", lines=(1, 3), **py),
+ _edge(rid, "app/diag.py::tick", "lib/poll.py::prune", call_lines=[2]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "lib/poll.py::prune", tmp_path)
+ assert row["line"] == 1
+ assert "call_line" not in row and "text" not in row
+
+
+ "language, ext, lines, text",
+ [
+ # An annotated JVM method starts on its annotation; a method reference calls.
+ ("java", "java", [" @Override", " public void tick() {",
+ " assertThrows(E.class, parser::prune);", " }"],
+ "assertThrows(E.class, parser::prune);"),
+ ("typescript", "ts", ["export function tick() {", " const r = prune<Hooks>(a);", "}"],
+ "const r = prune<Hooks>(a);"),
+ ("shell", "sh", ["tick() {", ' if prune "$dir"; then', " echo ok", " fi", "}"],
+ 'if prune "$dir"; then'),
+ ("swift", "swift", ["func tick() {", " prune?(item)", "}"], "prune?(item)"),
+ ],
+)
+async def test_each_language_call_form_is_served(
+ session, populated_db, tmp_path, language, ext, lines, text
+):
+ rid = populated_db
+ _write(tmp_path, f"app/diag.{ext}", lines)
+ session.add_all(
+ [
+ _sym(rid, f"lib/poll.{ext}::prune", lines=(10, 40), language=language),
+ _sym(rid, f"app/diag.{ext}::tick", lines=(1, len(lines)), language=language),
+ _edge(rid, f"app/diag.{ext}::tick", f"lib/poll.{ext}::prune",
+ call_lines=[next(n for n, t in enumerate(lines, 1) if "prune" in t)]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, f"lib/poll.{ext}::prune", tmp_path)
+ assert row["line"] == 1
+ assert row["text"] == text
+
+
+ "line, served",
+ [
+ (" prune_rows dir", True),
+ (" prune_rows(dir)", True),
+ # Known conservative gap: a bracketless call on a receiver is not read as a call.
+ (" store.prune_rows dir", False),
+ ],
+)
+async def test_ruby_command_calls(session, populated_db, tmp_path, line, served):
+ rid = populated_db
+ rb = {"language": "ruby"}
+ _write(tmp_path, "app/diag.rb", ["def tick", line, "end"])
+ session.add_all(
+ [
+ _sym(rid, "lib/poll.rb::prune_rows", lines=(10, 40), **rb),
+ _sym(rid, "app/diag.rb::tick", lines=(1, 3), **rb),
+ _edge(rid, "app/diag.rb::tick", "lib/poll.rb::prune_rows", call_lines=[2]),
+ ]
+ )
+ await session.flush()
+
+ (row,) = await _callers(session, rid, "lib/poll.rb::prune_rows", tmp_path)
+ assert row["line"] == 1
+ assert ("text" in row) is served
+
+
@pytest.mark.asyncio
async def test_call_through_an_import_alias_is_served(session, populated_db, tmp_path):
rid = populated_db
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index 1e64364ef..462d2ad9c 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -6,6 +6,8 @@ test data, mirroring the conftest pattern from the REST API tests.
from __future__ import annotations
+import re
+
import pytest
from repowise.core.persistence.search import strip_leading_headings
@@ -716,6 +718,62 @@ class TestSymbolTestPenalty:
assert self._score("spec/openapi/users.py", language="python") == base
+def test_symbol_coverage_folds_plurals_on_both_sides():
+ from repowise.core.persistence.models import WikiSymbol
+ from repowise.server.mcp_server.tool_search_symbols import _score_symbol, _tokens
+
+ def score(name: str, query: str) -> float:
+ row = WikiSymbol(name=name, qualified_name=name, file_path="src/a.py", language="python")
+ return _score_symbol(row, None, _tokens(query), query.lower())
+
+ # Every query word is covered once ``type`` meets ``types``, either way round.
+ full = score("declared_types_in", "declared types in")
+ assert score("declared_types_in", "declared type in") == full
+ assert score("parseHeader", "parse headers") == score("parseHeader", "parse header")
+ assert score("declared_types_in", "declared kind in") < full
+
+
+ "name, plural, singular",
+ [
+ ("MyClass", "my classes", "my class"),
+ ("createFactory", "create factories", "create factory"),
+ ("commandNameMatch", "command name matches", "command name match"),
+ ("cacheEntry", "cache entries", "cache entry"),
+ ("parseResponse", "parse responses", "parse response"),
+ ("statusCode", "status codes", "status code"),
+ ],
+)
+def test_irregular_s_plurals_reach_the_singular_name(name, plural, singular):
+ from repowise.core.persistence.models import WikiSymbol
+ from repowise.server.mcp_server.tool_search_symbols import (
+ _candidate_filter,
+ _score_symbol,
+ _tokens,
+ )
+
+ row = WikiSymbol(name=name, qualified_name=name, file_path="src/a.py", language="python")
+ assert _score_symbol(row, None, _tokens(plural), plural) == _score_symbol(
+ row, None, _tokens(singular), singular
+ )
+ # The candidate filter is a substring LIKE per singular form; the plural
+ # word's own forms must reach the name.
+ clause = _candidate_filter(_tokens(plural), plural)
+ sql = str(clause.compile(compile_kwargs={"literal_binds": True})).lower()
+ word = plural.split()[-1]
+ likes = set(re.findall(r"'%([^%']+)%'", sql))
+ assert any(like in name.lower() and like[:3] == word[:3] for like in likes)
+
+
+def test_a_singular_y_word_finds_its_ies_plural():
+ from repowise.server.mcp_server.tool_search_symbols import _candidate_filter, _tokens
+
+ clause = _candidate_filter(_tokens("create factory"), "create factory")
+ sql = str(clause.compile(compile_kwargs={"literal_binds": True})).lower()
+ assert any(like in "createfactories" and like.startswith("fact")
+ for like in re.findall(r"'%([^%']+)%'", sql))
+
+
class TestSymbolSearch:
"""mode="symbol" / "auto" routing into the structural index (issue #484)."""
diff --git a/tests/unit/server/mcp/test_verify_bounds.py b/tests/unit/server/mcp/test_verify_bounds.py
index 2c1d178e7..a9bf1227f 100644
--- a/tests/unit/server/mcp/test_verify_bounds.py
+++ b/tests/unit/server/mcp/test_verify_bounds.py
@@ -98,6 +98,42 @@ class TestNameAtLine:
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: