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
feat(answer): rank files named in a stack trace or by identifier in the question first (#3116)
Raghav Chamadiya43c13a5f34ac
diff --git a/packages/server/src/repowise/server/mcp_server/_query_shape.py b/packages/server/src/repowise/server/mcp_server/_query_shape.pyindex 83258590e..271d81ae9 100644--- a/packages/server/src/repowise/server/mcp_server/_query_shape.py+++ b/packages/server/src/repowise/server/mcp_server/_query_shape.py@@ -12,6 +12,8 @@ import refrom collections.abc import Containerfrom functools import cache+from repowise.server.mcp_server._stack_trace import parse_trace+@cachedef _code_exts() -> frozenset[str]:@@ -190,6 +192,35 @@ def _embedded_identifiers(query: str, names: Container[str] | None = None) -> li]+def _unmistakably_code(token: str) -> bool:+ """Dotted, snake_case, a digit, or a capital past the first letter beside+ a lowercase one. ``Config`` and ``Result`` are English words too."""+ if "." in token:+ return True+ body = token.strip("_")+ if "_" in body or any(ch.isdigit() for ch in body):+ return True+ return any(ch.islower() for ch in body) and any(ch.isupper() for ch in body[1:])+++def defined_identifiers(query: str, names: Container[str]) -> list[str]:+ """Code-shaped tokens of ``query`` (``_unmistakably_code``) that name an+ indexed symbol. ``names`` as for ``_embedded_identifiers``."""+ return [+ t+ for t in _embedded_identifiers(query, names)+ if _unmistakably_code(t) and _names_symbol(t, names)+ ]+++def is_issue_shaped(query: str, names: Container[str], frames: list | None = None) -> bool:+ """Whether ``query`` pastes a stack trace or names an identifier the index+ defines. ``frames`` is ``parse_trace(query)`` when the caller already has it."""+ if frames is None:+ frames = parse_trace(query)+ return bool(frames) or bool(defined_identifiers(query, names))++def _name_token_matches(query: str) -> list[re.Match[str]]:"""Words that could name a symbol: identifier-shaped, or dotted chains."""return [diff --git a/packages/server/src/repowise/server/mcp_server/_stack_trace.py b/packages/server/src/repowise/server/mcp_server/_stack_trace.pynew file mode 100644index 000000000..2892be0f2--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_stack_trace.py@@ -0,0 +1,179 @@+"""Stack-trace frames pasted into a question, and the repo files they name.++Stdlib only. Reads Python, JS/TS, Java/Kotlin, Go, Rust and C# traces.+Frames from the language runtime are dropped; frames from installed+dependencies (site-packages, node_modules, the Go module cache, the cargo+registry) are kept behind the user's frames, keyed on their package-relative+path, so a trace through an installed copy of this repo still lands on it.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from typing import NamedTuple+++class Frame(NamedTuple):+ path: str # forward slashes; a package-derived path or a bare file name+ line: int+ function: str | None+ vendored: bool = False+++_PY_RE = re.compile(r'File "([^"]+)", line (\d+)(?:, in ([^\s]+))?')+# JS/TS ``at f (path:l:c)`` / ``at path:l:c``; Rust ``at path.rs:l:c``.+_AT_COL_RE = re.compile(r"^\s*at (?:(.+?) \()?(\S+?):(\d+):(\d+)\)?\s*$")+_JAVA_RE = re.compile(r"^\s*at (?:[\w.@-]+/+)?([\w.$<>]+)\(([\w$]+\.(?:java|kt|kts|scala|groovy)):(\d+)\)")+_CS_RE = re.compile(r"^\s*at (.+?)\(.*?\) in (.+?):line (\d+)\s*$")+_GO_FILE_RE = re.compile(r"^\s+(\S+\.go):(\d+)(?: \+0x[0-9a-f]+)?\s*$")+_RUST_FUNC_RE = re.compile(r"^\s*\d+:\s+(?:0x[0-9a-f]+ - )?(\S+)\s*$")+_RUST_PANIC_RE = re.compile(r"panicked at (?:'.*?', )?([^\s:'][^\s:]*\.rs):(\d+):\d+")++_JVM_RUNTIME = ("java.", "javax.", "jdk.", "sun.", "com.sun.", "kotlin.", "kotlinx.", "scala.")+_DOTNET_RUNTIME = ("System.", "Microsoft.")++# Installed dependency roots: the path after the match is package-relative.+_VENDORED_RES = (+ re.compile(r"(?:^|/)(?:site|dist)-packages/(.+)$"),+ re.compile(r"(?:^|/)node_modules/(.+)$"),+ re.compile(r"(?:^|/)pkg/mod/([^@]+)@[^/]+/(.+)$"), # module path kept, version dropped+ re.compile(r"(?:^|/)\.cargo/registry/src/[^/]+/[^/]+/(.+)$"),+ re.compile(r"(?:^|/)\.cargo/git/checkouts/[^/]+/[^/]+/(.+)$"),+)+_RUNTIME_RES = (+ re.compile(r"^<.*>$"), # <frozen importlib._bootstrap>, <string>, <anonymous>+ re.compile(r"(?:^|/)lib/python\d[\d.]*/(?!.*(?:site|dist)-packages/)", re.IGNORECASE),+ re.compile(r"(?:^|/)python\d*/lib/(?!.*(?:site|dist)-packages/)", re.IGNORECASE),+ re.compile(r"^(?:node:|internal/|native\b)"),+ re.compile(r"(?:^|/)(?:go|libexec)/src/[^./]+/"), # GOROOT: no dot in the package root+ re.compile(r"^/rustc/|(?:^|/)\.rustup/"),+)+++def _classify(path: str) -> tuple[str, bool] | None:+ """``(path, vendored)`` for a frame worth keeping, ``None`` for runtime."""+ p = path.replace("\\", "/").removeprefix("file://").removeprefix("./")+ if any(r.search(p) for r in _RUNTIME_RES):+ return None+ for r in _VENDORED_RES:+ m = r.search(p)+ if m:+ return "/".join(m.groups()), True+ return p, False+++def _java_path(qualified: str, file_name: str) -> str:+ """``io.javalin.Javalin.start`` + ``Javalin.java`` -> ``io/javalin/Javalin.java``."""+ package = []+ for part in qualified.split(".")[:-1]:+ if part[:1].isupper():+ break+ package.append(part)+ return "/".join([*package, file_name])+++def _go_function(line: str) -> str | None:+ """``pkg.(*T).m(0xc0, {0x1})`` -> ``pkg.(*T).m``; the line above a Go file line."""+ s = re.sub(r" in goroutine \d+$", "", line.strip()).removeprefix("created by ")+ if s.endswith(")"):+ s = s[: s.rfind("(")]+ return s if s and " " not in s else None+++def _python(lines: list[str]) -> list[Frame]:+ frames = [+ Frame(m.group(1), int(m.group(2)), m.group(3))+ for line in lines+ if (m := _PY_RE.search(line))+ ]+ return frames[::-1] # printed outermost first+++def _innermost_first(lines: list[str]) -> list[Frame]:+ """JS/TS, Rust, Java/Kotlin, C# and Go: printed innermost first."""+ frames: list[Frame] = []+ for i, line in enumerate(lines):+ prev = lines[i - 1] if i else ""+ if m := _CS_RE.match(line):+ fn = m.group(1).strip()+ if not fn.startswith(_DOTNET_RUNTIME):+ frames.append(Frame(m.group(2), int(m.group(3)), fn))+ elif m := _JAVA_RE.match(line):+ fn = m.group(1)+ if not fn.startswith(_JVM_RUNTIME):+ frames.append(Frame(_java_path(fn, m.group(2)), int(m.group(3)), fn))+ elif m := _AT_COL_RE.match(line):+ fn = m.group(1)+ if fn is None and (rm := _RUST_FUNC_RE.match(prev)):+ fn = rm.group(1)+ frames.append(Frame(m.group(2), int(m.group(3)), fn))+ elif m := _GO_FILE_RE.match(line):+ frames.append(Frame(m.group(1), int(m.group(2)), _go_function(prev)))+ elif m := _RUST_PANIC_RE.search(line):+ frames.append(Frame(m.group(1), int(m.group(2)), None))+ return frames+++# Input bounds: a pasted log can be huge, and only its head carries the trace.+_MAX_CHARS = 20_000+_MAX_LINE = 500+_MAX_USER_FRAMES = 40+_MAX_VENDORED_FRAMES = 20+++def parse_trace(text: str) -> list[Frame]:+ """Frames in ``text``, innermost first: the user's frames, then installed+ dependencies'. Unique per ``(path, line, function)``; runtime frames dropped.++ Reads the first ``_MAX_CHARS`` only, blanks lines over ``_MAX_LINE`` before+ any regex sees them, and keeps at most 40 user and 20 dependency frames.+ """+ lines = ["" if len(line) > _MAX_LINE else line for line in text[:_MAX_CHARS].splitlines()]+ user: list[Frame] = []+ vendored: list[Frame] = []+ seen: set[tuple[str, int, str | None]] = set()+ for frame in (*_python(lines), *_innermost_first(lines)):+ kept = _classify(frame.path)+ if kept is None:+ continue+ path, is_vendored = kept+ key = (path, frame.line, frame.function)+ if key in seen:+ continue+ seen.add(key)+ (vendored if is_vendored else user).append(Frame(path, frame.line, frame.function, is_vendored))+ return user[:_MAX_USER_FRAMES] + vendored[:_MAX_VENDORED_FRAMES]+++def frame_basenames(frames: Iterable[Frame]) -> set[str]:+ return {f.path.rsplit("/", 1)[-1] for f in frames}+++# A file name more repo files share than this names none of them.+_MAX_AMBIGUOUS = 3+++def _segment_suffix(longer: str, shorter: str) -> bool:+ return longer == shorter or longer.endswith("/" + shorter)+++def map_to_repo_paths(frames: Iterable[Frame], indexed_paths: Iterable[str]) -> list[str]:+ """Repo files the frames name, in frame order, deduped.++ A frame matches an indexed path when either is a ``/``-bounded suffix of+ the other: an absolute frame ends with the repo path, a relative or+ package-derived one is the tail of it. A frame matching more than+ ``_MAX_AMBIGUOUS`` files is dropped. Vendored frames never match on a bare+ file name, which would only say some installed package has that file.+ """+ indexed = sorted({p.replace("\\", "/") for p in indexed_paths})+ out: list[str] = []+ for frame in frames:+ if frame.vendored and "/" not in frame.path:+ continue+ hits = [p for p in indexed if _segment_suffix(frame.path, p) or _segment_suffix(p, frame.path)]+ if len(hits) > _MAX_AMBIGUOUS:+ continue+ out.extend(h for h in hits if h not in out)+ return outdiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex 8259932c4..11151cd79 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@@ -178,6 +178,8 @@ from repowise.server.mcp_server.tool_answer.symbols import (_extract_value_answer,_hydrate_candidate_defines,_hydrate_symbols_for_hits,+ lead_with_files,+ place_named_files,)from repowise.server.mcp_server.tool_answer.synthesis import (_hash_answer_identity,@@ -187,6 +189,7 @@ from repowise.server.mcp_server.tool_answer.synthesis import (_resolve_reasoning_for_answer,synthesize,)+from repowise.server.mcp_server.tool_search_symbols import issue_files_log = logging.getLogger("repowise.mcp.answer")@@ -299,6 +302,20 @@ async def _run_retrieval_pipeline(# Demote noise (decisions on non-why, test pages on non-test questions)# below real pages. Non-dropping; after anchoring, which never injects noise.hits = _demote_noise_hits(hits, question, is_why=_is_why_question(question))+ # Files on a pasted stack trace lead; files defining a named identifier+ # join just below the top three. No-op when the question has neither.+ try:+ issue = await issue_files(ctx, question)+ except Exception:+ _log.warning("get_answer: issue file lookup failed", exc_info=True)+ else:+ def _in_scope(paths: list[str]) -> list[str]:+ return [p for p in paths if not scope or p.startswith(scope)]++ if traced := _in_scope(issue.traced):+ hits = lead_with_files(hits, traced)+ if named := _in_scope(issue.named):+ hits = place_named_files(hits, named)# The pre-cap ranking feeds ``candidates``: files below the synthesis cut# are still the best answer to "where do I look next".resolved_pool = list(hits)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.pyindex a499991ee..22b36e6a5 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@@ -332,6 +332,56 @@ async def _anchor_chosen_symbols()+def lead_with_files(hits: list[dict], paths: list[str]) -> list[dict]:+ """``hits`` led by ``paths`` in their order, each scored above every other+ hit; a path no hit carries is inserted as its file page."""+ by_path = {h.get("target_path"): h for h in hits}+ top = max((h.get("score", 0.0) for h in hits), default=0.0)+ base = max(top + 2.0, _HIGH_CONFIDENCE_SCORE_FLOOR + 1.0)+ led = [+ _boost_or_insert_file_hit(hits, by_path, path, base + len(paths) - i)+ for i, path in enumerate(paths)+ ]+ led_ids = {id(h) for h in led}+ return led + [h for h in hits if id(h) not in led_ids]+++# A file defining a named identifier is a milder signal than a trace frame: it+# joins just below the top three, and stays put when it already ranks there.+_NAMED_FILE_SLOT = 3+++def place_named_files(hits: list[dict], paths: list[str]) -> list[dict]:+ """``hits`` with each of ``paths`` outside the top three moved (or, when no+ hit carries it, inserted as its file page) to just below them, in order,+ scored level with the hit above."""+ out = list(hits)+ slot = _NAMED_FILE_SLOT+ for path in paths:+ idx = next((i for i, h in enumerate(out) if h.get("target_path") == path), None)+ if idx is not None and idx < slot:+ continue+ hit = out.pop(idx) if idx is not None else _file_page_hit(path, 0.0)+ pos = min(slot, len(out))+ if pos:+ hit["score"] = out[pos - 1].get("score", 0.0)+ out.insert(pos, hit)+ slot = pos + 1+ return out+++def _file_page_hit(path: str, score: float) -> dict:+ return {+ "page_id": f"file_page:{path}",+ "target_path": path,+ "title": path,+ "summary": "",+ "snippet": "",+ "page_type": "file_page",+ "score": score,+ }++def _boost_or_insert_file_hit(hits: list[dict], by_path: dict, path: str, score: float) -> dict:@@ -342,15 +392,7 @@ def _boost_or_insert_file_hit("""target = by_path.get(path)if target is None:- target = {- "page_id": f"file_page:{path}",- "target_path": path,- "title": path,- "summary": "",- "snippet": "",- "page_type": "file_page",- "score": score,- }+ target = _file_page_hit(path, score)hits.insert(0, target)by_path[path] = targetelse:diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex fb0446516..0324db0c4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -63,7 +63,9 @@ from repowise.server.mcp_server._query_shape import (from repowise.server.mcp_server._references import path_identity, symbol_identityfrom repowise.server.mcp_server._retrieval_rank import rerank_by_context_coveragefrom repowise.server.mcp_server.tool_search_symbols import (+ IssueFiles,indexed_names,+ issue_files,search_paths_single,search_symbols_single,)@@ -890,6 +892,17 @@ async def _contexts_for(repo: str | None) -> list:return [await _resolve_repo_context(repo)]+def _lead_candidates(response: dict, issue: IssueFiles | None, limit: int) -> None:+ """Trace files lead ``candidates``. A named identifier's defining file only+ fills a free slot after the ranked ones: ranked above them, it displaces+ better hits on ordinary questions. Capped at ``limit``."""+ if issue is None or not (issue.traced or issue.named):+ return+ ranked = [c["path"] for c in response.get("candidates") or []]+ paths = list(dict.fromkeys(issue.traced + ranked + issue.named))+ response["candidates"] = [{"path": p} for p in paths[:limit]]++def _tag_repo(items: list[dict], ctx, multi: bool) -> None:if multi:for item in items:@@ -1155,11 +1168,19 @@ async def search_codebase(names = await indexed_names(await _contexts_for(repo), query)grep_hint = _grep_hint_for(query, names)resolved_mode = _resolve_mode(query, mode, names)+ # Single repo only: a federated list has no one tree to name files in.+ issue: IssueFiles | None = None+ if repo != "all":+ try:+ issue = await issue_files(await _resolve_repo_context(repo), query, names)+ except Exception:+ _log.warning("search_codebase: issue file lookup failed", exc_info=True)if resolved_mode in ("symbol", "path", "hybrid"):structured = await _structured_search(query, limit, page_type, kind, symbol_kind, repo, resolved_mode, grep_hint, names)+ _lead_candidates(structured, issue, limit)attach_ignored_arguments(structured, ignored)return structured@@ -1246,6 +1267,7 @@ async def search_codebase(}if candidates := file_candidates(ranked, limit=limit):response["candidates"] = candidates+ _lead_candidates(response, issue, limit)if grep_hint and not output:response["grep_hint"] = grep_hintattach_ignored_arguments(response, ignored)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.pyindex 584022e47..25528da10 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@@ -19,7 +19,7 @@ graph node.from __future__ import annotationsimport re-from typing import Any+from typing import Any, NamedTuplefrom sqlalchemy import case, func, or_, select@@ -33,7 +33,18 @@ from repowise.server.mcp_server._helpers import (escape_like,is_excluded,)-from repowise.server.mcp_server._query_shape import _name_lookup_keys, _qual_norm+from repowise.server.mcp_server._query_shape import (+ _name_lookup_keys,+ _names_symbol,+ _qual_norm,+ defined_identifiers,+ is_issue_shaped,+)+from repowise.server.mcp_server._stack_trace import (+ frame_basenames,+ map_to_repo_paths,+ parse_trace,+)from repowise.server.mcp_server._symbol_lookup import symbol_rank_key# Candidate ceiling: scoring/sorting happens in Python, so the SQL pre-filter@@ -208,6 +219,104 @@ async def indexed_names(contexts: list, query: str) -> set[str]:return names | {name.lower() for name in names}+# Names so common, or so generic, that a definition of one says nothing about+# the question.+_COMMON_NAMES = frozenset(+ {"__init__", "__call__", "__main__", "main", "init", "test", "setup", "close", "start", "stop",+ "handle", "call", "name", "value", "data", "self", "index", "create", "update", "delete",+ "load", "save", "read", "write", "open", "parse", "build", "execute", "process", "invoke",+ "config", "result", "error", "client", "model", "utils", "types", "base", "manager",+ "handler", "options", "settings", "context", "request", "response"}+)+_MAX_NAMED_LOOKUPS = 5+# An identifier defined in more files than this names none of them.+_MAX_DEFINING_FILES = 3+# Basenames per query, so a long trace stays far under SQLite's expression limits.+_BASENAME_CHUNK = 20+++class IssueFiles(NamedTuple):+ traced: list[str] # on a pasted stack trace, innermost user frame first+ named: list[str] # defining an identifier the question names, not already traced+++def _named_lookups(text: str, names: set[str]) -> list[str]:+ out: list[str] = []+ for token in defined_identifiers(text, names):+ leaf = token.rsplit(".", 1)[-1]+ if len(leaf) >= 4 and leaf.lower() not in _COMMON_NAMES and leaf not in out:+ out.append(leaf)+ return out[:_MAX_NAMED_LOOKUPS]+++async def _traced_files(session, repo_id: str, frames: list) -> list[str]:+ bases = sorted(frame_basenames(frames))+ indexed: list[str] = []+ for i in range(0, len(bases), _BASENAME_CHUNK):+ res = await session.execute(+ select(GraphNode.node_id).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "file",+ or_(+ *(+ or_(+ GraphNode.node_id == base,+ GraphNode.node_id.like(f"%/{escape_like(base)}", escape=LIKE_ESCAPE),+ )+ for base in bases[i : i + _BASENAME_CHUNK]+ )+ ),+ )+ )+ indexed.extend(node_id for (node_id,) in res.all())+ return map_to_repo_paths(frames, indexed)+++async def _defining_files(session, repo_id: str, idents: list[str]) -> list[str]:+ res = await session.execute(+ select(WikiSymbol.name, WikiSymbol.file_path).where(+ WikiSymbol.repository_id == repo_id,+ func.lower(WikiSymbol.name).in_({i.lower() for i in idents}),+ )+ )+ rows = res.all()+ out: list[str] = []+ for ident in idents:+ files = sorted({fp for name, fp in rows if fp and _names_symbol(ident, {name, name.lower()})})+ if len(files) <= _MAX_DEFINING_FILES:+ out.extend(f for f in files if f not in out)+ return out+++async def issue_files(ctx: Any, text: str, names: set[str] | None = None) -> IssueFiles:+ """Files ``text`` names as an issue would: those on a pasted stack trace,+ and those defining an identifier it names.++ Empty when ``is_issue_shaped`` says no; then nothing past ``indexed_names``+ is queried. ``names`` is that set when the caller already loaded it. The+ trace is parsed once here and shared with the shape check.+ """+ frames = parse_trace(text)+ if names is None:+ names = await indexed_names([ctx], text)+ if not is_issue_shaped(text, names, frames):+ return IssueFiles([], [])+ idents = _named_lookups(text, names)+ traced: list[str] = []+ named: list[str] = []+ async with get_session(ctx.session_factory) as session:+ repository = await _get_repo(session)+ if frames:+ traced = await _traced_files(session, repository.id, frames)+ if idents:+ named = [p for p in await _defining_files(session, repository.id, idents) if p not in traced]+ spec = _get_exclude_spec(ctx.path)+ return IssueFiles(+ [p for p in traced if not is_excluded(p, spec)],+ [p for p in named if not is_excluded(p, spec)],+ )++async def search_symbols_single(ctx: Any,query: str,diff --git a/tests/unit/server/mcp/test_answer_issue_files.py b/tests/unit/server/mcp/test_answer_issue_files.pynew file mode 100644index 000000000..7aedfeaa6--- /dev/null+++ b/tests/unit/server/mcp/test_answer_issue_files.py@@ -0,0 +1,173 @@+"""Files a question names by stack trace or defined identifier lead retrieval.++``populated_db`` indexes ``src/auth/service.py`` (defines ``AuthService``),+``src/auth/middleware.py``, ``src/db/models.py`` and ``tests/test_service.py``.+"""++from __future__ import annotations++import pytest++TRACE = """\+Login fails with this:+Traceback (most recent call last):+ File "/srv/app/.venv/lib/python3.12/site-packages/starlette/routing.py", line 70, in app+ File "/srv/app/src/auth/middleware.py", line 33, in dispatch+ File "/usr/lib/python3.12/asyncio/base_events.py", line 691, in run_until_complete+KeyError: 'sub'+"""++_FAKE_FILES = [f"pkg/f{i}.py" for i in range(7)]+++def _patch_retrieval(monkeypatch, answer_mod) -> None:+ """Seven unrelated files rank first; none is a trace file."""++ async def _fake_retrieve(question, ctx):+ return [+ {"page_id": f"file_page:{p}", "score": 10.0 - i} for i, p in enumerate(_FAKE_FILES)+ ]++ async def _fake_hydrate(hits, ctx, *, scope=None):+ for h in hits:+ h["target_path"] = h["page_id"].removeprefix("file_page:")+ h.update(title=h["target_path"], summary="", snippet="", page_type="file_page")+ return hits++ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)+++async def _pool(answer_mod, question: str) -> tuple[list[str], list[str]]:+ from repowise.core.persistence.database import get_session+ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context++ ctx = await _resolve_repo_context(None)+ async with get_session(ctx.session_factory) as session:+ repo_id = (await _get_repo(session)).id+ got = await answer_mod._run_retrieval_pipeline(+ question, ctx, scope=None, exclude_spec=None, repo_id=repo_id+ )+ return [h.get("target_path") for h in got.resolved_pool], [h.get("target_path") for h in got.hits]+++async def test_trace_file_outside_top_five_leads(setup_mcp, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod++ _patch_retrieval(monkeypatch, answer_mod)+ pool, hits = await _pool(answer_mod, TRACE)+ assert pool[0] == "src/auth/middleware.py"+ assert hits[0] == "src/auth/middleware.py"+ assert len(hits) == 5+++async def test_trace_files_then_defined_identifier_files(setup_mcp, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod++ _patch_retrieval(monkeypatch, answer_mod)+ pool, _ = await _pool(answer_mod, TRACE + "\nIs AuthService caching the token?")+ # The symbol anchor already lifts AuthService's file; the trace file leads.+ assert pool[0] == "src/auth/middleware.py"+ assert "src/auth/service.py" in pool[1:4]+++async def test_plain_question_ranking_unchanged(setup_mcp, monkeypatch):+ import repowise.server.mcp_server.tool_answer.answer as answer_mod++ _patch_retrieval(monkeypatch, answer_mod)+ calls: list = []+ monkeypatch.setattr(answer_mod, "lead_with_files", lambda *a: calls.append(a))+ monkeypatch.setattr(answer_mod, "place_named_files", lambda *a: calls.append(a))+ question = "How are expired login tokens refreshed?"+ pool, _ = await _pool(answer_mod, question)+ assert calls == []+ assert pool == _FAKE_FILES+++async def _no_wait(ctx) -> None:+ return None+++async def test_search_candidates_lead_with_trace_file(setup_mcp, monkeypatch):+ import repowise.server.mcp_server.tool_search as search_mod++ monkeypatch.setattr(search_mod, "_wait_for_vector_store", _no_wait)+ result = await search_mod.search_codebase(TRACE)+ assert result["candidates"][0] == {"path": "src/auth/middleware.py"}+ assert len(result["candidates"]) <= 5+++async def test_search_plain_query_candidates_untouched(setup_mcp, monkeypatch):+ import repowise.server.mcp_server.tool_search as search_mod++ calls: list = []+ real = search_mod._lead_candidates++ def _spy(response, issue, limit):+ calls.append(issue)+ return real(response, issue, limit)++ monkeypatch.setattr(search_mod, "_lead_candidates", _spy)+ monkeypatch.setattr(search_mod, "_wait_for_vector_store", _no_wait)+ await search_mod.search_codebase("how are tokens refreshed")+ assert calls == [([], [])]+++def _hit(path: str, score: float) -> dict:+ return {"page_id": f"file_page:{path}", "target_path": path, "score": score}+++def test_named_file_joins_below_top_three():+ from repowise.server.mcp_server.tool_answer.symbols import place_named_files++ hits = [_hit(f"f{i}.py", 10.0 - i) for i in range(6)]+ out = place_named_files(hits, ["f5.py", "new.py"])+ assert [h["target_path"] for h in out] == [+ "f0.py", "f1.py", "f2.py", "f5.py", "new.py", "f3.py", "f4.py"+ ]+ assert out[3]["score"] == out[2]["score"]+ assert out[4]["page_type"] == "file_page"+++def test_named_file_already_in_top_three_stays():+ from repowise.server.mcp_server.tool_answer.symbols import place_named_files++ hits = [_hit(f"f{i}.py", 10.0 - i) for i in range(4)]+ out = place_named_files(hits, ["f1.py"])+ assert [h["target_path"] for h in out] == ["f0.py", "f1.py", "f2.py", "f3.py"]+++def test_search_named_files_only_fill_free_slots():+ from repowise.server.mcp_server.tool_search import _lead_candidates+ from repowise.server.mcp_server.tool_search_symbols import IssueFiles++ response = {"candidates": [{"path": f"f{i}.py"} for i in range(3)]}+ _lead_candidates(response, IssueFiles(["trace.py"], ["f2.py", "def.py", "x.py"]), 5)+ assert response["candidates"] == [+ {"path": p} for p in ["trace.py", "f0.py", "f1.py", "f2.py", "def.py"]+ ]+ full = {"candidates": [{"path": f"f{i}.py"} for i in range(5)]}+ _lead_candidates(full, IssueFiles([], ["def.py"]), 5)+ assert full["candidates"] == [{"path": f"f{i}.py"} for i in range(5)]+++async def test_long_trace_queries_basenames_in_chunks(setup_mcp):+ """60 distinct basenames span three lookups; the real frame still maps."""+ from repowise.server.mcp_server._helpers import _resolve_repo_context+ from repowise.server.mcp_server.tool_search_symbols import issue_files++ deps = [+ f' File "/srv/.venv/lib/python3.12/site-packages/dep/m{i}.py", line 1, in g'+ for i in range(25)+ ]+ user = [f' File "/srv/app/pkg/mod{i}.py", line 1, in f' for i in range(45)]+ real = ' File "/srv/app/src/auth/middleware.py", line 33, in dispatch'+ lines = ["Traceback (most recent call last):", *deps, *user, real, "KeyError: 'sub'"]+ issue = await issue_files(await _resolve_repo_context(None), "\n".join(lines))+ assert issue.traced == ["src/auth/middleware.py"]diff --git a/tests/unit/server/mcp/test_stack_trace.py b/tests/unit/server/mcp/test_stack_trace.pynew file mode 100644index 000000000..ea6489ccb--- /dev/null+++ b/tests/unit/server/mcp/test_stack_trace.py@@ -0,0 +1,255 @@+"""Stack-trace frames in a question, mapped onto repo files."""++from __future__ import annotations++import pytest++from repowise.server.mcp_server._query_shape import is_issue_shaped+from repowise.server.mcp_server._stack_trace import Frame, map_to_repo_paths, parse_trace++PYTHON = """\+Traceback (most recent call last):+ File "/home/dev/proj/.venv/lib/python3.12/site-packages/flask/app.py", line 1536, in __call__+ return self.wsgi_app(environ, start_response)+ File "/usr/lib/python3.12/threading.py", line 1010, in run+ self._target(*self._args)+ File "<frozen importlib._bootstrap>", line 1360, in _find_and_load+ File "/home/dev/proj/src/shop/views.py", line 41, in checkout+ total = cart.total()+ File "/home/dev/proj/src/shop/cart.py", line 12, in total+ return sum(i.price for i in self.items)+TypeError: unsupported operand type(s)+"""++JS = """\+TypeError: Cannot read properties of undefined (reading 'get')+ at Hono.dispatch (file:///home/dev/hono/src/hono-base.ts:412:22)+ at /home/dev/hono/src/compose.ts:51:17+ at /home/dev/app/node_modules/undici/lib/fetch/index.js:200:5+ at processTicksAndRejections (node:internal/process/task_queues:95:5)+ at async Promise.all (index 0)+"""++JAVA = """\+Exception in thread "main" java.lang.IllegalStateException: Server already started+\tat io.javalin.Javalin.start(Javalin.java:180)+\tat java.base/java.lang.Thread.run(Thread.java:833)+\tat app//io.javalin.http.servlet.JavalinServlet.service(JavalinServlet.kt:89) ~[javalin-6.1.jar:6.1]+\tat org.eclipse.jetty.server.Server.handle(Server.java:516)+\tat kotlin.collections.CollectionsKt.first(Collections.kt:200)+\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)+"""++GO = """\+panic: runtime error: invalid memory address or nil pointer dereference+[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4b2c1a]++goroutine 1 [running]:+github.com/spf13/cobra.(*Command).execute(0xc0000f8300, {0xc000020090, 0x1, 0x1})+\t/home/dev/go/pkg/mod/github.com/spf13/[email protected]/command.go:983 +0x8f+runtime.gopanic({0x5a1b20, 0x6c2f40})+\t/usr/local/go/src/runtime/panic.go:914 +0x21f+main.main()+\t/home/dev/proj/cmd/tool/main.go:10 +0x25+"""++RUST = """\+thread 'main' panicked at crates/searcher/src/searcher/glue.rs:123:9:+called `Option::unwrap()` on a `None` value+stack backtrace:+ 0: rust_begin_unwind+ at /rustc/90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf/library/std/src/panicking.rs:597:5+ 1: core::option::unwrap_failed+ at /home/dev/.rustup/toolchains/stable/lib/rustlib/src/rust/library/core/src/option.rs:1985:5+ 2: grep_searcher::searcher::glue::ReadByLine::run+ at ./crates/searcher/src/searcher/glue.rs:123:9+ 3: serde::de::Deserialize::deserialize+ at /home/dev/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.190/src/de/mod.rs:500:9+"""++RUST_OLD_PANIC = "thread 'main' panicked at 'index out of bounds', src/main.rs:5:5"++CSHARP = """\+System.InvalidOperationException: Sequence contains no elements+ at System.Linq.ThrowHelper.ThrowNoElementsException()+ at Polly.Retry.RetryResilienceStrategy`1.ExecuteCore[TState](Func`3 callback) in C:\\build\\Polly\\src\\Polly.Core\\Retry\\RetryResilienceStrategy.cs:line 54+ at Polly.ResiliencePipeline.ExecuteAsync() in /_/src/Polly.Core/ResiliencePipeline.Async.cs:line 31+ at Microsoft.Extensions.Http.Something.Send()+"""+++ ("text", "expected"),+ [+ (+ PYTHON,+ [+ Frame("/home/dev/proj/src/shop/cart.py", 12, "total"),+ Frame("/home/dev/proj/src/shop/views.py", 41, "checkout"),+ Frame("flask/app.py", 1536, "__call__", True),+ ],+ ),+ (+ JS,+ [+ Frame("/home/dev/hono/src/hono-base.ts", 412, "Hono.dispatch"),+ Frame("/home/dev/hono/src/compose.ts", 51, None),+ Frame("undici/lib/fetch/index.js", 200, None, True),+ ],+ ),+ (+ JAVA,+ [+ Frame("io/javalin/Javalin.java", 180, "io.javalin.Javalin.start"),+ Frame(+ "io/javalin/http/servlet/JavalinServlet.kt",+ 89,+ "io.javalin.http.servlet.JavalinServlet.service",+ ),+ Frame(+ "org/eclipse/jetty/server/Server.java", 516, "org.eclipse.jetty.server.Server.handle"+ ),+ ],+ ),+ (+ GO,+ [+ Frame("/home/dev/proj/cmd/tool/main.go", 10, "main.main"),+ Frame(+ "github.com/spf13/cobra/command.go",+ 983,+ "github.com/spf13/cobra.(*Command).execute",+ True,+ ),+ ],+ ),+ (+ RUST,+ [+ Frame("crates/searcher/src/searcher/glue.rs", 123, None),+ Frame("crates/searcher/src/searcher/glue.rs", 123, "grep_searcher::searcher::glue::ReadByLine::run"),+ Frame("src/de/mod.rs", 500, "serde::de::Deserialize::deserialize", True),+ ],+ ),+ (RUST_OLD_PANIC, [Frame("src/main.rs", 5, None)]),+ (+ CSHARP,+ [+ Frame(+ "C:/build/Polly/src/Polly.Core/Retry/RetryResilienceStrategy.cs",+ 54,+ "Polly.Retry.RetryResilienceStrategy`1.ExecuteCore[TState]",+ ),+ Frame(+ "/_/src/Polly.Core/ResiliencePipeline.Async.cs", 31, "Polly.ResiliencePipeline.ExecuteAsync"+ ),+ ],+ ),+ ],+ ids=["python", "js", "java", "go", "rust", "rust_old_panic", "csharp"],+)+def test_parse_trace(text: str, expected: list[Frame]) -> None:+ assert parse_trace(text) == expected+++def test_plain_question_has_no_frames() -> None:+ assert parse_trace("How does the router match a path like /users/:id at runtime?") == []+++INDEXED = [+ "src/shop/cart.py",+ "src/shop/views.py",+ "src/flask/app.py",+ "src/hono-base.ts",+ "src/compose.ts",+ "javalin/src/main/java/io/javalin/Javalin.java",+ "javalin/src/main/java/io/javalin/http/servlet/JavalinServlet.kt",+ "command.go",+ "crates/searcher/src/searcher/glue.rs",+ "src/Polly.Core/Retry/RetryResilienceStrategy.cs",+ "src/Polly.Core/ResiliencePipeline.Async.cs",+ "a/util.py",+ "b/util.py",+ "c/util.py",+ "d/util.py",+]+++ ("text", "expected"),+ [+ (PYTHON, ["src/shop/cart.py", "src/shop/views.py", "src/flask/app.py"]),+ (JS, ["src/hono-base.ts", "src/compose.ts"]),+ (+ JAVA,+ [+ "javalin/src/main/java/io/javalin/Javalin.java",+ "javalin/src/main/java/io/javalin/http/servlet/JavalinServlet.kt",+ ],+ ),+ (GO, ["command.go"]),+ (RUST, ["crates/searcher/src/searcher/glue.rs"]),+ (+ CSHARP,+ ["src/Polly.Core/Retry/RetryResilienceStrategy.cs", "src/Polly.Core/ResiliencePipeline.Async.cs"],+ ),+ ],+ ids=["python", "js", "java", "go", "rust", "csharp"],+)+def test_map_to_repo_paths(text: str, expected: list[str]) -> None:+ assert map_to_repo_paths(parse_trace(text), INDEXED) == expected+++def test_ambiguous_basename_kept_up_to_three() -> None:+ three = [Frame("util.py", 1, None)]+ assert map_to_repo_paths(three, INDEXED[11:14]) == ["a/util.py", "b/util.py", "c/util.py"]+ assert map_to_repo_paths(three, INDEXED[11:]) == []+++def test_unrelated_absolute_frame_does_not_match_by_basename() -> None:+ frames = [Frame("/home/dev/other/app.py", 3, "main")]+ assert map_to_repo_paths(frames, ["src/flask/app.py"]) == []+++NAMES = frozenset({"AuthService", "authservice", "login"})+++class TestIsIssueShaped:+ def test_trace(self) -> None:+ assert is_issue_shaped(RUST_OLD_PANIC, set())++ def test_defined_identifier(self) -> None:+ assert is_issue_shaped("Why does AuthService reject a valid token?", NAMES)++ def test_code_shaped_but_undefined(self) -> None:+ assert not is_issue_shaped("Why does TokenRefreshScheduler stall?", NAMES)++ def test_capitalised_english_word_is_not_an_identifier(self) -> None:+ names = NAMES | {"Config", "config"}+ assert not is_issue_shaped("Why does `Config` reject a valid token?", names)++ def test_shares_parsed_frames(self) -> None:+ assert is_issue_shaped("no trace text here", set(), frames=[Frame("a.py", 1, None)])++ def test_plain_question(self) -> None:+ assert not is_issue_shaped("How are tokens refreshed?", NAMES)+++def test_input_is_bounded() -> None:+ frame = ' File "/srv/app/x.py", line 1, in f\n'+ assert parse_trace("x\n" * 15_000 + frame) == [] # past the first 20k chars+ assert parse_trace(frame.rstrip("\n") + " " * 600) == []+ many = "".join(f' File "/srv/app/m{i}.py", line 1, in f\n' for i in range(100))+ deps = "".join(f' File "/v/site-packages/d/m{i}.py", line 1, in f\n' for i in range(50))+ frames = parse_trace(many + deps)+ assert sum(not f.vendored for f in frames) == 40+ assert sum(f.vendored for f in frames) == 20+ assert frames[0].path == "/srv/app/m99.py" # innermost kept+++def test_generic_and_plain_words_are_not_looked_up() -> None:+ from repowise.server.mcp_server.tool_search_symbols import _named_lookups++ names = {"config", "Result", "result", "load_config", "AuthService", "authservice"}+ text = "app.config is None in load_config; Result comes back empty from AuthService"+ assert _named_lookups(text, names) == ["load_config", "AuthService"]