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(answer): reach function bodies by rare terms and literals, and stop trusting an off-topic exact name (#3736)

Swati Ahuja7c58bfedea1f
diff --git a/packages/server/src/repowise/server/mcp_server/_line_hits.py b/packages/server/src/repowise/server/mcp_server/_line_hits.py
index ea8eca055..6f612637f 100644
--- a/packages/server/src/repowise/server/mcp_server/_line_hits.py
+++ b/packages/server/src/repowise/server/mcp_server/_line_hits.py
@@ -238,6 +238,14 @@ def _scan_listed(root: Path, needle: str, word: bool) -> tuple[list[dict[str, An
return rows, reasons + scan_reasons
+def production_lines(root: Path, token: str) -> list[dict[str, Any]]:
+ """The word-bounded lines holding *token* in production files, from the
+ same scan a literal search runs. For get_answer, which reads live lines
+ the wiki never rendered (function bodies, string literals)."""
+ rows, _reasons = _scan_listed(root, token, True)
+ return [r for r in rows if _scan_rank(r["path"]) == 0]
+
+
def scan_literal(
root: Path, files: list[str], needle: str, word: bool
) -> tuple[list[dict[str, Any]], list[str]]:
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 3255fdebd..736bb8316 100644
--- a/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/_prose_symbols.py
@@ -58,7 +58,7 @@ from repowise.server.mcp_server._helpers import (
)
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 STOPWORDS
+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 (
_symbol_kind_for_request_kind,
@@ -101,6 +101,11 @@ _NAME_COVER_MIN_SHARE = 2 / 3
# specific as a page hit. Two words (``test_matcher``) often name a role, not a topic.
_FULL_COVER_MIN_WORDS = 3
+# Words of a question the symbol leg ranks by rarity before keeping
+# ``_MAX_TERMS`` of them. Ranking reads the in-memory name postings, so the
+# pool is cheap; the cap only bounds a pasted stack trace.
+_TERM_POOL = 32
+
class _SymbolTextIndex(NamedTuple):
"""One repo's symbols as plain text, by position, for in-process matching."""
@@ -203,6 +208,22 @@ def _name_words(name: str | None) -> set[str]:
return {_stem(t) for t in _tokens(name) if t not in STOPWORDS}
+def _rarest_terms(index: _SymbolTextIndex, terms: list[str], keep: int) -> list[str]:
+ """The *keep* terms fewest symbol names carry, rarest first.
+
+ Length is a poor stand-in for specificity: ``resolution`` outlasts
+ ``alias`` though far more names carry it. A compound counts as its rarest
+ word. A term no name carries can only match a path, so it goes last.
+ """
+
+ def name_count(term: str) -> int:
+ words = _name_words(term)
+ return min((len(index.postings.get(w, ())) for w in words), default=0)
+
+ counts = {t: name_count(t) for t in terms}
+ return sorted(terms, key=lambda t: (counts[t] == 0, counts[t], -len(t), t))[:keep]
+
+
def _name_covered(row: WikiSymbol, terms: Iterable[str]) -> bool:
"""Whether the question's words make up most of *row*'s name."""
words = _name_words(row.name)
@@ -274,13 +295,15 @@ async def search_symbols_by_terms(
limit: int,
*,
kind: str | None = None,
+ max_terms: int | None = None,
) -> list[dict]:
"""Rank indexed symbols against the content words of a question.
The prose-side counterpart to
:func:`tool_search_symbols.search_symbols_single`, which needs the caller
to have typed an identifier. Returns the same result shape, so a caller
- can interleave the two without special-casing either.
+ can interleave the two without special-casing either. ``max_terms`` keeps
+ only that many of *terms*, the rarest among symbol names.
"""
terms = [t for t in terms if t]
if not terms:
@@ -289,6 +312,8 @@ async def search_symbols_by_terms(
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
index = await _symbol_text_index(session, repository.id)
+ if max_terms is not None:
+ terms = _rarest_terms(index, terms, max_terms)
matched: dict[str, set[str]] = {}
saturated: set[str] = set()
for term in terms:
@@ -378,11 +403,11 @@ async def symbol_backed_pages(
Never raises: a missing or slow symbol index leaves the page retrievers to
answer on their own, which is the behaviour that shipped before this.
"""
- terms = content_terms(question)
+ terms = content_terms(question, max_terms=_TERM_POOL)
if not terms or max_files <= 0:
return []
try:
- symbols = await search_symbols_by_terms(ctx, terms, symbol_limit)
+ symbols = await search_symbols_by_terms(ctx, terms, symbol_limit, max_terms=_MAX_TERMS)
except Exception:
return []
if not symbols:
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 7994a8c0d..81461e243 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
@@ -300,6 +300,7 @@ async def _run_retrieval_pipeline(
hits,
repo_root=_anchor_root,
session_factory=ctx.session_factory,
+ question=question,
)
# Concept anchoring: a why/value question pinning a number to a behaviour
# anchors the file whose source comment justifies that number.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
index 32bd79fb5..56e2ba88a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
@@ -49,7 +49,11 @@ def _gather_body_candidates(
if not path:
continue
for s in h.get("_anchor_symbols") or []:
- if _selection_names(s.get("name"), answer_text, anchor_names):
+ # A def anchored by a literal it holds is selected by that literal too.
+ if any(
+ _selection_names(n, answer_text, anchor_names)
+ for n in (s.get("name"), s.get("_named_by"))
+ ):
candidates.append((0, _kind_rank(s), s.get("start_line") or 0, path, s))
# Tier 1 catches symbols only the prose names; the degraded mode has none.
if anchor_names is not None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
index 1a77795fc..1acc5150a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
@@ -77,6 +77,21 @@ _HOMONYM_UNION_BODY_MAX_LINES = 120
# cases is wide, so this is not tuned to an exact count.
_HOMONYM_UNION_PROSE_DEF_CEILING = 6
+# Exact-identifier trust. On a prose question, a definition named by the
+# question but outside these top retrieved files must earn its anchor: its
+# location shares a word with the question, or the identifier is specific.
+_ANCHOR_TOPICAL_FILES = 5
+# An identifier written in more production files than this names a role many
+# files share (a field, a parameter, a local), not one definition. Both the
+# trust rule above and the literal leg below read it.
+_SPECIFIC_TOKEN_MAX_FILES = 3
+# Identifier-shaped words naming no indexed symbol (a string literal, a key, an
+# environment variable) are scanned for in live source, and the definitions
+# holding them anchored, up to the inline-body cap. Scans per question:
+_LITERAL_SCAN_MAX_TOKENS = 3
+# Definition kinds an exact question name may anchor.
+_ANCHOR_KINDS = ("function", "method", "class", "interface")
+
# Data-shape grounding: "what fields does each entry in <blob> contain" is
# answered by mining the field set from source, precision-ordered:
# * a documented {...} shape near the identifier (confidence high);
@@ -290,7 +305,9 @@ _ANSWER_COVERAGE_FLOOR = 0.5
# 20: caller questions carry ``graph_callers`` and synthesise with them.
# 21: impact questions carry ``graph_neighbors``, the users of the lead file.
# 22: ``confidence`` also asks whether the top hit covers the question's words.
-_ANSWER_SCHEMA_VERSION = 22
+# 23: bodies include the function holding a literal the question writes, and an
+# exact name off the topic no longer anchors its definition.
+_ANSWER_SCHEMA_VERSION = 23
# Above this a whole-file Read costs more than the answer, so the low-confidence
# hint names a ranged Read or a skeleton instead.
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 072e73ac1..3bc4f4cbe 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
@@ -8,7 +8,9 @@ here, since callers and tests import them from this module.
from __future__ import annotations
+import asyncio
import re
+from collections import Counter
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any
@@ -16,15 +18,26 @@ from typing import Any
from sqlalchemy import select
from repowise.core.persistence.models import WikiSymbol
-from repowise.server.mcp_server._query_shape import _WORD_CHAIN_RE, _identifier_shaped
+from repowise.core.test_paths import is_test_related_path
+from repowise.server.mcp_server._line_hits import production_lines
+from repowise.server.mcp_server._query_shape import (
+ _WORD_CHAIN_RE,
+ _identifier_shaped,
+ _looks_like_code_name,
+)
from repowise.server.mcp_server._query_terms import split_humps
from repowise.server.mcp_server._verify import verify_and_heal
from repowise.server.mcp_server.tool_answer.config import (
+ _ANCHOR_KINDS,
+ _ANCHOR_TOPICAL_FILES,
_ENRICH_TOP_N_HITS,
_HIGH_CONFIDENCE_SCORE_FLOOR,
_HOMONYM_UNION_BODY_MAX_LINES,
_HOMONYM_UNION_CHAR_BUDGET,
_HOMONYM_UNION_PROSE_DEF_CEILING,
+ _INLINE_BODY_MAX_SYMBOLS,
+ _LITERAL_SCAN_MAX_TOKENS,
+ _SPECIFIC_TOKEN_MAX_FILES,
_STOPWORDS,
)
from repowise.server.mcp_server.tool_answer.hydration import ( # noqa: F401 re-exported
@@ -70,7 +83,7 @@ from repowise.server.mcp_server.tool_answer.withheld import ( # noqa: F401 re-
_match_definition,
withheld_definitions,
)
-from repowise.server.mcp_server.tool_search import _prose_dominates
+from repowise.server.mcp_server.tool_search import _is_test_query, _prose_dominates
def _extract_question_identifiers(question: str) -> set[str]:
@@ -213,6 +226,7 @@ async def _anchor_symbol_hits(
hits: list[dict],
repo_root: Path | None = None,
session_factory: Any = None,
+ question: str = "",
) -> tuple[list[dict], dict[str, Any]]:
"""Inject the defining file of a question-named indexed symbol into hits.
@@ -242,14 +256,15 @@ async def _anchor_symbol_hits(
select(WikiSymbol).where(
WikiSymbol.repository_id == repo_id,
WikiSymbol.name.in_(list(question_ids)),
- WikiSymbol.kind.in_(("function", "method", "class", "interface")),
)
)
by_name: dict[str, list] = {}
+ indexed_names: set[str] = set()
for row in res.scalars().all():
+ indexed_names.add(row.name)
# A pathless row names nothing the reply can point at: drop it from
# every route below.
- if not row.file_path:
+ if not row.file_path or row.kind not in _ANCHOR_KINDS:
continue
by_name.setdefault(row.name, []).append(row)
@@ -272,14 +287,135 @@ async def _anchor_symbol_hits(
d["_approx"] = True
return d
+ literal: dict[str, list] = {}
+ if question and repo_root is not None and not is_symbol_lookup_question(question, question_ids):
+ guard = _TopicGuard(repo_root, hits, question, qids_lower)
+ by_name = await _trusted_over_topic(by_name, qids_lower, guard)
+ literal = await _literal_holders(session, repo_id, question_ids - indexed_names, guard)
+
chosen = await _choose_anchor_symbols(by_name, qids_lower, _verified_dict, homonyms)
- if not chosen:
+ if not chosen and not literal:
return hits, homonyms
await _anchor_chosen_symbols(hits, chosen, _verified_dict)
+ for token, rows in literal.items():
+ await _anchor_chosen_symbols(hits, rows, _verified_dict, named_by=token)
hits.sort(key=lambda h: h.get("score", 0.0), reverse=True)
return hits, homonyms
+class _TopicGuard:
+ """Whether an identifier the question writes may anchor a def over the topic.
+
+ An exact name alone is not enough on a prose question: ``module_path`` can
+ name one def in a provider spec and a field in fifty files, and a test
+ fixture shares its name with the local it stands in for. A def is trusted
+ when its file is among the top retrieved files, when few production files
+ write the identifier (it names one thing), or when its file name or owner
+ shares a word with the rest of the question. Off the top files, a test def
+ is trusted only by a question about tests.
+ """
+
+ def __init__(self, root: Path, hits: list[dict], question: str, qids_lower: set[str]):
+ self.root = root
+ self.topical = {
+ h["target_path"] for h in hits[:_ANCHOR_TOPICAL_FILES] if h.get("target_path")
+ }
+ named = set().union(*(_text_stems(q) for q in qids_lower))
+ self.topic_stems = _text_stems(question) - named
+ self.about_tests = _is_test_query(question)
+ self._lines: dict[str, list[dict]] = {}
+
+ async def lines(self, token: str) -> list[dict]:
+ """Production lines writing *token*, scanned at most once per question."""
+ if token not in self._lines:
+ self._lines[token] = await asyncio.to_thread(production_lines, self.root, token)
+ return self._lines[token]
+
+ async def trusts(self, token: str, row) -> bool:
+ if row.file_path in self.topical:
+ return True
+ # Before the count: a name only tests write counts zero production files.
+ if is_test_related_path(row.file_path) and not self.about_tests:
+ return False
+ files = len({r["path"] for r in await self.lines(token)})
+ if (files or self.about_tests) and files <= _SPECIFIC_TOKEN_MAX_FILES:
+ return True
+ stem = row.file_path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
+ owner = f"{stem} {row.parent_name or ''} {row.name or ''}"
+ return bool(self.topic_stems & _text_stems(owner))
+
+
+async def _trusted_over_topic(
+ by_name: dict[str, list], qids_lower: set[str], guard: _TopicGuard
+) -> dict[str, list]:
+ """*by_name* without the defs an exact name may not anchor (see :class:`_TopicGuard`).
+
+ A def whose parent the question names is the one it means, so it stays.
+ """
+ kept: dict[str, list] = {}
+ for name, cands in by_name.items():
+ trusted = [
+ c
+ for c in cands
+ if _question_names_parent(c, qids_lower) or await guard.trusts(name, c)
+ ]
+ if trusted:
+ kept[name] = trusted
+ return kept
+
+
+async def _literal_holders(
+ session, repo_id: str, tokens: set[str], guard: _TopicGuard
+) -> dict[str, list]:
+ """The functions holding an identifier the index does not define, by identifier.
+
+ A string literal or a key (``"retry_after"``) lives in a function body, so
+ no page and no symbol name carries it. A holder must pass the same guard
+ as a named def; holders in top retrieved files rank first, then by how
+ many of the lines they hold, at most ``_INLINE_BODY_MAX_SYMBOLS`` overall.
+ """
+ # Code-shaped only: ``Authorization`` or ``JVMs`` is a word prose writes too.
+ plain = sorted(
+ (t for t in tokens if "." not in t and _looks_like_code_name(t)),
+ key=lambda t: (-len(t), t),
+ )
+ lines = {t: rows for t in plain[:_LITERAL_SCAN_MAX_TOKENS] if (rows := await guard.lines(t))}
+ if not lines:
+ return {}
+ res = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path.in_({r["path"] for rows in lines.values() for r in rows}),
+ WikiSymbol.kind.in_(("function", "method")),
+ )
+ )
+ defs = [d for d in res.scalars().all() if d.start_line and d.end_line]
+ found: list[tuple[tuple, str, Any]] = []
+ for token, rows in lines.items():
+ for d, n in _innermost_holders(defs, rows).items():
+ if await guard.trusts(token, d):
+ key = (d.file_path not in guard.topical, -n, d.file_path, d.start_line)
+ found.append((key, token, d))
+ found.sort(key=lambda t: t[0])
+ out: dict[str, list] = {}
+ for _key, token, d in found[:_INLINE_BODY_MAX_SYMBOLS]:
+ out.setdefault(token, []).append(d)
+ return out
+
+
+def _innermost_holders(defs: list, rows: list[dict]) -> Counter:
+ """How many of *rows* each def holds, counting a line for its innermost def only."""
+ # Comment lines count on purpose: httpx writes NO_PROXY only in its holder's comments.
+ held: Counter = Counter()
+ for r in rows:
+ spans = [
+ d for d in defs if d.file_path == r["path"] and d.start_line <= r["line"] <= d.end_line
+ ]
+ if spans:
+ held[max(spans, key=lambda d: d.start_line)] += 1
+ return held
+
+
def _question_names_parent(cand, qids_lower: set[str]) -> bool:
"""Whether the question names this def's parent, or a qualifier of it."""
if (cand.parent_name or "").lower() in qids_lower:
@@ -333,8 +469,13 @@ async def _anchor_chosen_symbols(
hits: list[dict],
chosen: list,
verified_dict: Callable[[Any], Awaitable[dict]],
+ named_by: str | None = None,
) -> None:
- """Boost (or insert) each chosen def's file and stash the def on it."""
+ """Boost (or insert) each chosen def's file and stash the def on it.
+
+ ``named_by`` is the identifier the question wrote when the def holds it
+ rather than being named by it.
+ """
by_path = {h.get("target_path"): h for h in hits}
top_score = max((h.get("score", 0.0) for h in hits), default=0.0)
# Above the current top: an exact symbol match is stronger than prose.
@@ -358,6 +499,7 @@ async def _anchor_chosen_symbols(
"kind": sym.kind,
"start_line": vd["start_line"],
"end_line": vd["end_line"],
+ **({"_named_by": named_by} if named_by else {}),
}
)
diff --git a/tests/unit/server/mcp/test_answer_topic_guard.py b/tests/unit/server/mcp/test_answer_topic_guard.py
new file mode 100644
index 000000000..585682909
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_topic_guard.py
@@ -0,0 +1,205 @@
+"""get_answer retrieval: rare symbol-leg terms, the literal leg, and the topic guard.
+
+A question's identifier anchors a definition only when the topic agrees; an
+identifier the index does not define (a string literal, a key) anchors the
+function holding it, so ``symbol_bodies`` serves the body the wiki never
+rendered.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.mcp_server._hit_symbols import _stem
+from repowise.server.mcp_server._prose_symbols import _rarest_terms, _SymbolTextIndex
+from repowise.server.mcp_server.tool_answer.bodies import _gather_body_candidates
+from repowise.server.mcp_server.tool_answer.symbols import _anchor_symbol_hits
+
+
+class _Sym:
+ def __init__(self, name, file_path, start_line, end_line, kind="function", parent_name=None):
+ self.name = name
+ self.file_path = file_path
+ self.kind = kind
+ self.parent_name = parent_name
+ self.qualified_name = name
+ self.start_line = start_line
+ self.end_line = end_line
+ self.symbol_id = f"{file_path}::{name}"
+
+
+class _Result:
+ def __init__(self, rows):
+ self._rows = rows
+
+ def scalars(self):
+ return self
+
+ def all(self):
+ return self._rows
+
+
+class _Session:
+ """Answers each query with the next row list: by name, then by file."""
+
+ def __init__(self, *answers):
+ self._answers = list(answers)
+
+ async def execute(self, *a, **k):
+ return _Result(self._answers.pop(0) if self._answers else [])
+
+
+_SPEC = "class Spec:\n def module_path(self):\n return 1\n"
+
+
+def _write(root, rel, text):
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+def _index(counts: dict[str, int]) -> _SymbolTextIndex:
+ """Name postings carrying each word *counts* times, keyed as the index keys them."""
+ return _SymbolTextIndex((), (), (), {_stem(w): tuple(range(n)) for w, n in counts.items()})
+
+
+def test_rarest_terms_keep_the_rare_word_over_the_long_one():
+ # ``resolution`` is longer but six names carry it; ``alias`` only one.
+ index = _index({"resolution": 6, "alias": 1, "call": 2})
+ kept = _rarest_terms(index, ["resolution", "alias", "call", "unheard"], 2)
+ assert kept == ["alias", "call"]
+
+
+def test_rarest_terms_rank_a_compound_by_its_rarest_word():
+ index = _index({"module": 9, "alias": 1})
+ assert _rarest_terms(index, ["module", "module_alias"], 1) == ["module_alias"]
+
+
+async def test_a_name_written_across_the_repo_does_not_anchor_an_off_topic_def(tmp_path):
+ _write(tmp_path, "providers/specs.py", _SPEC)
+ for i in range(4):
+ _write(tmp_path, f"core/user{i}.py", f"module_path = {i}\n")
+ row = _Sym("module_path", "providers/specs.py", 2, 3, kind="method", parent_name="Spec")
+ hits = [{"target_path": "core/imports.py", "score": 3.0}]
+ out, homonyms = await _anchor_symbol_hits(
+ _Session([row]),
+ "r",
+ {"module_path"},
+ hits,
+ repo_root=tmp_path,
+ question="how are wildcard import bindings consumed (module_path)?",
+ )
+ assert out[0]["target_path"] == "core/imports.py"
+ assert not any(h.get("_anchor_symbols") for h in out)
+ assert not homonyms["union"]
+
+
+async def test_a_specific_name_still_anchors_a_def_retrieval_missed(tmp_path):
+ _write(tmp_path, "providers/specs.py", _SPEC)
+ row = _Sym("module_path", "providers/specs.py", 2, 3, kind="method", parent_name="Spec")
+ hits = [{"target_path": "core/imports.py", "score": 3.0}]
+ out, _ = await _anchor_symbol_hits(
+ _Session([row]),
+ "r",
+ {"module_path"},
+ hits,
+ repo_root=tmp_path,
+ question="how are wildcard import bindings consumed (module_path)?",
+ )
+ assert out[0]["target_path"] == "providers/specs.py"
+ assert out[0]["_anchor_symbols"][0]["name"] == "module_path"
+
+
+async def test_test_fixtures_sharing_a_production_name_are_not_the_answer(tmp_path):
+ for i in range(4):
+ _write(tmp_path, f"pipeline/stage{i}.py", f"parsed_files = [{i}]\n")
+ for i in range(2):
+ _write(tmp_path, f"tests/test_walk{i}.py", "def parsed_files():\n return []\n")
+ rows = [_Sym("parsed_files", f"tests/test_walk{i}.py", 1, 2) for i in range(2)]
+ hits = [{"target_path": "pipeline/stage0.py", "score": 3.0}]
+ out, homonyms = await _anchor_symbol_hits(
+ _Session(rows),
+ "r",
+ {"parsed_files"},
+ hits,
+ repo_root=tmp_path,
+ question="Is a manifest included in parsed_files during the ingestion walk?",
+ )
+ assert not homonyms["union"]
+ assert not any(h.get("_anchor_symbols") for h in out)
+
+
+async def test_a_bare_lookup_keeps_trusting_the_name(tmp_path):
+ for i in range(4):
+ _write(tmp_path, f"pipeline/stage{i}.py", f"parsed_files = [{i}]\n")
+ _write(tmp_path, "tests/test_walk.py", "def parsed_files():\n return []\n")
+ row = _Sym("parsed_files", "tests/test_walk.py", 1, 2)
+ out, _ = await _anchor_symbol_hits(
+ _Session([row]), "r", {"parsed_files"}, [], repo_root=tmp_path, question="parsed_files"
+ )
+ assert out[0]["target_path"] == "tests/test_walk.py"
+
+
+async def test_a_literal_no_symbol_names_anchors_the_function_holding_it(tmp_path):
+ source = (
+ "def _pick_origin(call):\n"
+ " if call.alias:\n"
+ ' return "module_alias"\n'
+ " return None\n"
+ )
+ _write(tmp_path, "core/resolver.py", source)
+ holder = _Sym("_pick_origin", "core/resolver.py", 1, 4)
+ hits = [{"target_path": "core/other.py", "score": 3.0}]
+ out, _ = await _anchor_symbol_hits(
+ _Session([], [holder]),
+ "r",
+ {"module_alias"},
+ hits,
+ repo_root=tmp_path,
+ question="where is the module_alias resolution origin set?",
+ )
+ assert out[0]["target_path"] == "core/resolver.py"
+ [anchor] = out[0]["_anchor_symbols"]
+ assert anchor["name"] == "_pick_origin" and anchor["_named_by"] == "module_alias"
+ # The keyless reply selects bodies by the question's identifiers.
+ [picked] = _gather_body_candidates(out, "", anchor_names={"module_alias"})
+ assert picked[4]["name"] == "_pick_origin"
+
+
+async def test_a_prose_word_is_not_scanned_for(tmp_path):
+ _write(tmp_path, "core/auth.py", 'def strip(h):\n h.pop("Authorization")\n')
+ holder = _Sym("strip", "core/auth.py", 1, 2)
+ out, _ = await _anchor_symbol_hits(
+ _Session([], [holder]),
+ "r",
+ {"Authorization"},
+ [{"target_path": "core/other.py", "score": 3.0}],
+ repo_root=tmp_path,
+ question="where is the Authorization header removed on redirect?",
+ )
+ assert not any(h.get("_anchor_symbols") for h in out)
+
+
+
+async def test_a_name_only_tests_write_does_not_anchor_a_fixture(tmp_path):
+ # No production file writes the name, which must not read as "specific".
+ _write(tmp_path, "core/ingest.py", "def walk():\n return []\n")
+ _write(tmp_path, "tests/test_walk.py", "def walked_paths():\n return []\n")
+ row = _Sym("walked_paths", "tests/test_walk.py", 1, 2)
+ out, homonyms = await _anchor_symbol_hits(
+ _Session([row]),
+ "r",
+ {"walked_paths"},
+ [{"target_path": "core/ingest.py", "score": 3.0}],
+ repo_root=tmp_path,
+ question="does the ingestion walk include walked_paths for manifests?",
+ )
+ assert not homonyms["union"]
+ assert not any(h.get("_anchor_symbols") for h in out)