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
perf(mcp): serve one location per search_codebase row (#3317)
Aman79bb8c9e4506
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 1543eb149..30d018351 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -221,7 +221,7 @@ Hybrid search that routes by the shape of the query: identifiers search the symb| `page_type` | string | none | One page type, usually `file_page` or `module_page` || `repo` | string | default repo | Workspace repo alias, or `"all"` to search every repo |-**Key return fields:** `results` (every row that names a file carries it in `path`, and a row naming no file has no `path`; symbol hits carry `symbol_id`, line bounds and `signature`, plus `symbols` (`name:line` of up to five other matches in that file, then `+N more`) when several matched; concept hits carry `relevance_score`, `snippet` and `sources`; `file` on symbol and file hits is a deprecated alias of `path`, removed in the next minor release, and a page keeps `target_path` only where it differs from `path`), `candidates` (up to `limit` distinct openable file paths, best first). If your next move is a Read, read `candidates`: some `results` are pages that are not files.+**Key return fields:** `results` (every row that names a file carries it in `path`, and a row naming no file has no `path`; symbol hits carry `symbol_id`, line bounds and `signature`, plus `symbols` (`name:line` of up to five other matches in that file, then `+N more`) when several matched; concept hits carry `relevance_score` and `snippet`, plus `sources` unless it would be `["fts"]` on an index without embeddings; a row leaves off `page_id` and a structural `title` (`File: <path>`) where `page_type` plus `symbol_id` or `path` rebuild them; the old `file` alias is gone, and a page keeps `target_path` only where it differs from `path`), `candidates` (up to `limit` distinct openable file paths, best first). If your next move is a Read, read `candidates`: some `results` are pages that are not files.**Page rows** also carry `symbols`: up to three `name:line` entries (`Owner.member` for members) in that file whose names match the query's words. The first three page rows whose file has a matching line also carry `matched_lines`: a sample of up to three `{line, text}` source lines read from the live file that share the most query words, code lines before comments and imports. Unlike `lines`, it is never every match.diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 2f6ed488f..03bcaa82d 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -184,12 +184,11 @@ Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor c| Field | Meaning ||-------|---------|-| `results` | Ranked hits. Symbol hits: `type: "symbol"`, `symbol_id`, `name`, `kind`, `path`, `start_line`, `end_line`, `signature`, `next: "get_symbol"`. File hits: `type: "file"`, `page_id`, `path`, `title`, `next: "get_context"`. Concept hits: wiki pages with `page_type`, `path` when the page names a file, `relevance_score`, `snippet`, `sources` |+| `results` | Ranked hits. Symbol hits: `type: "symbol"`, `symbol_id`, `name`, `kind`, `path`, `start_line`, `end_line`, `signature`, `next: "get_symbol"`. File hits: `type: "file"`, `page_id`, `path`, `title`, `next: "get_context"`. Concept hits: wiki pages with `page_type`, `path` when the page names a file, `symbol_id` on a symbol page, `relevance_score`, `snippet`. `page_id` and `title` are left off a row that can rebuild them: the id is `{page_type}:{symbol_id or path}`, and a structural title is `File: <path>` / `Symbol: <symbol_id>` in the repo's page language. Prose titles (module, onboarding, overview) stay || `path` | The repo-relative file a row names, openable as is. Absent when the row names no file (a module page's group key, an onboarding slot, the repo overview); never a page id |-| `file` | Deprecated alias of `path` on symbol and file hits (and on a `symbol_spotlight` page). Removed in the next minor release || `target_path` | On a page hit, kept only where it is not the same string as `path`: a page with no `path` keeps its group key, slot or repo name here. Where it is dropped, `page_id` stays || `symbols` | On a symbol hit outside `symbol` mode: up to five other matching symbols in the same file, as `name:line`, then a `+N more` entry counting the rest. Those matches share the row instead of taking slots of their own |-| `sources` | The retrievers that found a concept hit: `fts`, `vector`, or both. A hit found by `fts` alone has no semantic agreement |+| `sources` | The retrievers that found a concept hit: `fts`, `vector`, `symbol` or a combination. Omitted when it would be `["fts"]` and `_meta.semantic_search` is `false`, since the reply already says retrieval is full-text-only || `candidates` | Up to `limit` distinct openable file paths, best first |Outside `mode="symbol"`, `limit` caps distinct files: hits are collapsed to one row per file, best row first, and the freed slots go to the next pages, then the next symbols. This includes concept mode, where a file page and a `symbol_spotlight` page of the same file are one row. `mode="symbol"` keeps one row per symbol, so overloads in one file each list.diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.pyindex 4490e5662..aa73db989 100644--- a/packages/cli/src/repowise/cli/commands/search_cmd.py+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py@@ -67,6 +67,16 @@ def _result_kind(item: dict) -> str:return kind if kind in ("symbol", "file") else "page"+def _row_title(item: dict) -> str:+ """The row's title, or the location it names when the server omitted it.++ The server drops a structural title (``File: a.py``) because ``path`` and+ ``symbol_id`` already say it, so a table that wants a title column reads+ the location instead.+ """+ return item.get("title") or item.get("symbol_id") or item.get("path") or ""++def _project_result(item: dict, *, multi: bool) -> dict:"""One tool result, trimmed to the keys this command has always emitted.@@ -77,12 +87,12 @@ def _project_result(item: dict, *, multi: bool) -> dict:========== ==============================================================page ``score`` (from ``relevance_score``), ``title``, ``page_type``,- ``path`` (from ``target_path``), ``snippet``- symbol ``score``, ``name``, ``qualified_name``, ``kind``, ``path``- (from ``file``), ``line`` (from ``start_line``), and+ ``path`` (``target_path`` for a pathless page), ``snippet``+ symbol ``score``, ``name``, ``qualified_name``, ``kind``, ``path``,+ ``line`` (from ``start_line``), and``symbol_id`` — the id ``repowise symbol`` takes, withoutwhich a symbol hit cannot be followed anywhere- file ``score``, ``title``, ``path`` (from ``file``)+ file ``score``, ``title``, ``path``========== ==============================================================Dropped: ``page_id``, ``sources``, ``confidence_score``, ``end_line``,@@ -103,31 +113,22 @@ def _project_result(item: dict, *, multi: bool) -> dict:"name": item.get("name") or "","qualified_name": item.get("qualified_name") or "","kind": item.get("kind") or "",- "path": item.get("path") or item.get("file") or "",+ "path": item.get("path") or "","line": item.get("start_line"),"symbol_id": item.get("symbol_id") or "",})elif kind == "file":- path = item.get("path") or item.get("file") or ""- out.update({"title": item.get("title") or "", "path": path})+ out.update({"title": _row_title(item), "path": item.get("path") or ""})else:out.update({- "title": item.get("title") or "",+ "title": _row_title(item),"page_type": item.get("page_type") or "","path": item.get("path") or item.get("target_path") or "","snippet": item.get("snippet") or "",})- # ``target_path`` on a symbol_spotlight is a page id (``a.py::Foo``),- # not something a reader can open, which is why the tool attaches- # ``file`` beside it. ``path`` keeps the tool's own value so the- # payload stays what it was; ``file`` carries the openable resolution- # and appears only when the two differ.- file = item.get("file")- if file and file != out["path"]:- out["file"] = fileif multi:out["repo"] = item.get("repo") or ""return outdiff --git a/packages/core/src/repowise/core/generation/structural_labels.py b/packages/core/src/repowise/core/generation/structural_labels.pyindex 8095fffde..baa6f00b1 100644--- a/packages/core/src/repowise/core/generation/structural_labels.py+++ b/packages/core/src/repowise/core/generation/structural_labels.py@@ -349,3 +349,16 @@ def structural_page_title(language: str | None, page_type: str, target: str) ->*target* is a path or a qualified symbol name and is never translated."""return f"{resolve_structural_labels(language)[_TITLE_LABEL_KEYS[page_type]]}: {target}"+++def is_structural_title(language: str | None, page_type: str, target: str, title: str | None) -> bool:+ """True when *title* is exactly what :func:`structural_page_title` would store.++ A structural title only restates the page's own target in a localized+ wrapper, so a caller that still has the target can rebuild it and need not+ ship it. False for a page type with no structural title and for a title that+ differs in any way (an edited or prose title carries information).+ """+ if page_type not in _TITLE_LABEL_KEYS or not target or not title:+ return False+ return title == structural_page_title(language, page_type, target)diff --git a/packages/core/src/repowise/core/sessions/adapters/codex.py b/packages/core/src/repowise/core/sessions/adapters/codex.pyindex 26486c014..6c6d903c4 100644--- a/packages/core/src/repowise/core/sessions/adapters/codex.py+++ b/packages/core/src/repowise/core/sessions/adapters/codex.py@@ -367,7 +367,7 @@ def _bind_first_file(tool: ToolUse, results: list[dict[str, str]]) -> None:if not isinstance(tool.input, dict) or tool.input.get("path"):returnfor result in results:- file_path = (result.get("path") or result.get("file")) if isinstance(result, dict) else None+ file_path = result.get("path") if isinstance(result, dict) else Noneif isinstance(file_path, str) and file_path:tool.input["path"] = file_pathreturn@@ -446,8 +446,8 @@ def _rewrite_search_output(output: Any) -> dict | None:path = line.replace("\\", "/")else:continue- # Both keys, as search_codebase serves them while ``file`` is an alias.- results.append({"path": path, "file": path})+ # ``path`` alone, as search_codebase serves it now that ``file`` is gone.+ results.append({"path": path})return {"result": {"results": results}}diff --git a/packages/core/src/repowise/core/sessions/miners/demand.py b/packages/core/src/repowise/core/sessions/miners/demand.pyindex 7b73034a2..39ce825bd 100644--- a/packages/core/src/repowise/core/sessions/miners/demand.py+++ b/packages/core/src/repowise/core/sessions/miners/demand.py@@ -147,7 +147,6 @@ def _search_files(result: dict[str, Any]) -> list[str]:continuehit = (item.get("path")- or item.get("file")or item.get("target_path")or item.get("symbol_id"))diff --git a/packages/server/src/repowise/server/mcp_server/_page_paths.py b/packages/server/src/repowise/server/mcp_server/_page_paths.pyindex 6e249c1fc..39753b1ab 100644--- a/packages/server/src/repowise/server/mcp_server/_page_paths.py+++ b/packages/server/src/repowise/server/mcp_server/_page_paths.py@@ -98,15 +98,16 @@ def add_row_paths(rows: list[dict]) -> list[dict]:The last step before a search response leaves. A row naming no file (amodule page's group key, an onboarding slot) gets no ``path`` at all.- Transition aliases until the next minor release: ``file`` stays where it- was, and a page's ``target_path`` stays only where it is not the same- string as ``path``.+ ``path`` is the one place a row names its file, so the deprecated ``file``+ alias is removed here once ``path`` has been read from it, and a page's+ ``target_path`` stays only where it is not the same string as ``path``."""for row in rows:path = hit_file_path(row)if not path:continuerow["path"] = path+ row.pop("file", None)if row.get("page_type") and row.get("target_path") == path:del row["target_path"]return rowsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex fa69adb8c..298fa3c0c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -11,6 +11,7 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.generation.structural_labels import is_structural_titlefrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -48,7 +49,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._hit_symbols import attach_hit_symbolsfrom repowise.server.mcp_server._line_hits import attach_line_hits-from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT+from repowise.server.mcp_server._meta import EXHAUSTIVE_SWEEP_HINT, semantic_search_statefrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._page_paths import (FILE_ROW_TYPES,@@ -567,7 +568,13 @@ def _drop_derivable_page_ids(results: list[dict]) -> list[dict]:as ``"file_page:"`` and kept its id."""for item in results:- target = item.get("target_path") or item.get("path", "")+ # A symbol page's id ends in ``::Symbol`` and ``_attach_paths`` moved that+ # half into ``symbol_id``, so ``target_path`` is only its file.+ target = (+ item.get("symbol_id")+ if item.get("page_type") == "symbol_spotlight"+ else None+ ) or item.get("target_path") or item.get("path", "")derived = f"{item.get('page_type', '')}:{target}"# A row for a file with no page has an id that names no page.if item.get("page_id") == derived or item.get("page_type") == PAGELESS_FILE:@@ -575,6 +582,48 @@ def _drop_derivable_page_ids(results: list[dict]) -> list[dict]:return results+def _page_language(ctx) -> str:+ """The language *ctx*'s structural page titles were generated in."""+ try:+ from repowise.core.repo_config import load_repo_config++ return str(load_repo_config(ctx.path).get("language") or "en")+ except Exception:+ return "en"+++def _slim_served_rows(+ rows: list[dict], languages: dict[str | None, str] | None = None+) -> list[dict]:+ """The last step before a search reply leaves: one location per row.++ ``path`` (plus ``symbol_id`` on symbol rows) is the row's only location, so+ ``file``, a ``page_id`` that rebuilds from them, and a ``title`` that is just+ the structural label wrapped around them are all dropped. Each is dropped+ only where the caller can provably rebuild it. ``sources: ["fts"]`` goes when+ the reply's own ``_meta.semantic_search`` already says retrieval is+ full-text-only; an index with embeddings is unchanged.++ *languages* maps a row's ``repo`` alias (``None`` for a single-repo reply) to+ the language its titles were generated in.+ """+ add_row_paths(rows)+ _drop_derivable_page_ids(rows)+ fts_only = semantic_search_state() is False+ for row in rows:+ target = row.get("symbol_id") or row.get("path")+ if target and is_structural_title(+ (languages or {}).get(row.get("repo"), "en"),+ row.get("page_type", ""),+ target,+ row.get("title"),+ ):+ row.pop("title", None)+ if fts_only and row.get("sources") == ["fts"]:+ row.pop("sources", None)+ return rows++def _serve_snippets(results: list[dict]) -> None:"""Drop each snippet's leading page heading, after ranking has read it."""for item in results:@@ -879,8 +928,7 @@ async def _federated_search(if candidates := file_candidates(all_results, limit=limit):response["candidates"] = candidates# Last, so nothing above has to know the field is on its way out.- add_row_paths(output)- _drop_derivable_page_ids(output)+ _slim_served_rows(output, {ctx.alias: _page_language(ctx) for ctx in contexts})_serve_snippets(output)return response@@ -1185,8 +1233,10 @@ async def _structured_search(response["grep_hint"] = grep_hint# Last, so nothing above has to know the field is on its way out. Paths# first, so a page whose target_path is dropped keeps its page_id.- add_row_paths(results)- _drop_derivable_page_ids(results)+ _slim_served_rows(+ results,+ {(ctx.alias if multi else None): _page_language(ctx) for ctx in contexts},+ )_serve_snippets(results)return response@@ -1380,7 +1430,6 @@ async def search_codebase(await attach_line_hits(response, query, resolved_mode, names, repo)attach_ignored_arguments(response, ignored)# Last, so nothing above has to know the field is on its way out.- add_row_paths(output)- _drop_derivable_page_ids(output)+ _slim_served_rows(output, {None: _page_language(ctx)})_serve_snippets(output)return responsediff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex 0cad839bd..9333d5b9c 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -403,11 +403,14 @@ export interface ChangeRiskArtifact extends ArtifactEnvelopeIdentity {export interface SearchResultsArtifactData {query: string;results: Array<{- title: string;+ /** Omitted when it only restates `path`/`symbol_id` (a structural title). */+ title?: string;page_type: string;page_id?: string;/** Openable repo-relative file; absent when the hit names no file. */path?: string;+ /** `path::Symbol` on a symbol page. */+ symbol_id?: string;/** Kept only where it differs from `path` or `path` is absent. */target_path?: string;snippet?: string;diff --git a/packages/ui/__tests__/chat/source-citations.test.tsx b/packages/ui/__tests__/chat/source-citations.test.tsxindex 9cb964592..d76ecd721 100644--- a/packages/ui/__tests__/chat/source-citations.test.tsx+++ b/packages/ui/__tests__/chat/source-citations.test.tsx@@ -160,6 +160,42 @@ describe("extractSources", () => {expect(sources[0]?.targetPath).toBe("src/auth.py");});+ it("cites a slimmed file row that has only page_type and path", () => {+ // No page_id, no target_path and no structural title: the file name stands in.+ const sources = extractSources(+ [searchCall([{ page_type: "file_page", path: "src/auth.py" }])],+ "repo1",+ );++ expect(sources).toHaveLength(1);+ expect(sources[0]?.pageId).toBe("file_page:src/auth.py");+ expect(sources[0]?.title).toBe("auth.py");+ });++ it("rebuilds a symbol page's id from symbol_id, not its file", () => {+ const sources = extractSources(+ [+ searchCall([+ {+ page_type: "symbol_spotlight",+ symbol_id: "src/auth.py::login",+ path: "src/auth.py",+ },+ { page_type: "file_page", path: "src/auth.py" },+ ]),+ ],+ "repo1",+ );++ // The symbol page and its file page are two distinct citations.+ expect(sources.map((s) => s.pageId)).toEqual([+ "symbol_spotlight:src/auth.py::login",+ "file_page:src/auth.py",+ ]);+ expect(sources[0]?.title).toBe("src/auth.py::login");+ expect(sources[0]?.targetPath).toBe("src/auth.py");+ });+it("cites files from get_why health stale_decisions", () => {const sources = extractSources([diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsxindex 7aecc8b83..78b80d469 100644--- a/packages/ui/src/chat/artifacts.tsx+++ b/packages/ui/src/chat/artifacts.tsx@@ -631,11 +631,11 @@ export function SearchResultsRenderer({<SectionTitle icon={Search}>{data.query}</SectionTitle>{data.results.map((r, i) => (<div- key={`${r.page_id ?? r.title}:${i}`}+ key={`${r.page_id ?? r.symbol_id ?? r.path ?? r.title}:${i}`}className="rounded-lg border border-[var(--color-border-default)] p-3"><div className="text-xs font-medium text-[var(--color-text-primary)]">- {r.title}+ {r.title ?? r.symbol_id ?? r.path}</div><div className="text-xs text-[var(--color-text-tertiary)] mt-0.5">{getPageTypeLabel(r.page_type)}diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsxindex fd73553e3..e9eefb14c 100644--- a/packages/ui/src/chat/source-citations.tsx+++ b/packages/ui/src/chat/source-citations.tsx@@ -54,24 +54,30 @@ export function extractSources(if (tc.name === "search_codebase") {const results = (result.results as Array<Record<string, unknown>>) ?? [];for (const r of results) {- // `page_id` is `${page_type}:${target_path}`, and the tool now omits it- // wherever those two rebuild it. Derive rather than skip: the previous- // `const pageId = r.page_id` dropped the whole row — and its citation —- // for any result without one. Same fallback the get_context branch uses.- // The tool also drops `target_path` where it equals `path`, so fall back- // to `path`, the same way the server builds the id it compares against.+ // `page_id` is `${page_type}:${symbol_id ?? path}`, and the tool omits+ // it (and a structural `title`) wherever those rebuild it. Derive rather+ // than skip, or the row and its citation would vanish. A page's+ // `target_path` is also dropped where it equals `path`, so fall back to+ // `path`, the same way the server builds the id it compares against.const pageType = r.page_type as string | undefined;+ const symbolId = r.symbol_id as string | undefined;const targetPath =(r.target_path as string | undefined) || (r.path as string | undefined);+ const idTarget =+ pageType === "symbol_spotlight" && symbolId ? symbolId : targetPath;const pageId =(r.page_id as string | undefined) ??- (pageType && targetPath ? `${pageType}:${targetPath}` : "");+ (pageType && idTarget ? `${pageType}:${idTarget}` : "");if (!pageId || seen.has(pageId)) continue;seen.add(pageId);sources.push({id: `${tc.id}:${pageId}`,pageId,- title: (r.title as string) ?? pageId,+ title:+ (r.title as string | undefined) ??+ symbolId ??+ targetPath?.split("/").pop() ??+ pageId,pageType: (r.page_type as string) ?? "file_page",targetPath: targetPath ?? "",confidence: r.confidence_score as number | undefined,diff --git a/tests/fixtures/mcp/retrieval_guard_baseline.json b/tests/fixtures/mcp/retrieval_guard_baseline.jsonindex eb2f7b20c..05bbf179e 100644--- a/tests/fixtures/mcp/retrieval_guard_baseline.json+++ b/tests/fixtures/mcp/retrieval_guard_baseline.json@@ -3,34 +3,34 @@"answer": {"cov@1": 0.7708,"cov@5": 0.9479,- "cov_all": 0.9688,+ "cov_all": 0.9583,"files": 5.0,- "precision": 0.2698,- "tokens": 1364.5+ "precision": 0.2669,+ "tokens": 705.0},"answer_synth": {"cov@1": 0.7917,"cov@5": 0.9479,"cov_all": 0.9479,"files": 4.0,- "precision": 0.2955,+ "precision": 0.2966,"tokens": 351.0},"search": {- "cov@1": 0.8125,- "cov@5": 0.9201,- "cov_all": 0.9201,- "files": 5.0,- "precision": 0.4333,- "tokens": 603.0+ "cov@1": 0.8333,+ "cov@5": 0.9306,+ "cov_all": 0.9306,+ "files": 4.0,+ "precision": 0.5399,+ "tokens": 531.5},"search_limit10": {"cov@1": 0.8333,- "cov@5": 0.8889,- "cov_all": 0.9306,- "files": 7.5,- "precision": 0.3385,- "tokens": 1139.0+ "cov@5": 0.9097,+ "cov_all": 0.9514,+ "files": 4.5,+ "precision": 0.4751,+ "tokens": 910.5}}}diff --git a/tests/unit/cli/test_output_agent_readiness.py b/tests/unit/cli/test_output_agent_readiness.pyindex 83ff92950..73e958002 100644--- a/tests/unit/cli/test_output_agent_readiness.py+++ b/tests/unit/cli/test_output_agent_readiness.py@@ -171,7 +171,7 @@ def test_symbol_json_keeps_the_id_the_next_command_takes() -> None:"symbol_id": f"{LONG_PATH}::LanceDBVectorStore","name": "LanceDBVectorStore","kind": "class",- "file": LONG_PATH,+ "path": LONG_PATH,"start_line": 60,"end_line": 240,"signature": "class LanceDBVectorStore(VectorStore)",diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.pyindex 6a4293b01..16c341ec2 100644--- a/tests/unit/cli/test_search_collapse.py+++ b/tests/unit/cli/test_search_collapse.py@@ -48,7 +48,7 @@ SYMBOL_HIT = {"symbol_id": "packages/cli/src/repowise/cli/output.py::resolve_console_width","name": "resolve_console_width","kind": "function",- "file": "packages/cli/src/repowise/cli/output.py",+ "path": "packages/cli/src/repowise/cli/output.py","start_line": 44,"end_line": 72,"signature": "def resolve_console_width(stream) -> int | None",@@ -62,7 +62,7 @@ FILE_HIT = {"type": "file","page_id": "file:packages/cli/src/repowise/cli/helpers.py","title": "File: packages/cli/src/repowise/cli/helpers.py",- "file": "packages/cli/src/repowise/cli/helpers.py",+ "path": "packages/cli/src/repowise/cli/helpers.py","score": 140.0,"next": "get_context",}@@ -280,29 +280,27 @@ def test_page_results_keep_exactly_the_payload_this_command_always_emitted():assert dropped not in json.dumps(out["results"]), f"{dropped} survived the trim"-def test_a_symbol_spotlight_hit_carries_the_openable_file_beside_its_page_id():- """``target_path`` on a symbol_spotlight is ``a.py::Foo`` — a page id, not- something a reader can open — which is why the tool attaches ``file``."""- hit = {**PAGE_HIT, "page_type": "symbol_spotlight",- "target_path": "packages/cli/src/repowise/cli/output.py::resolve_console_width",- "file": "packages/cli/src/repowise/cli/output.py"}- row = project({"results": [hit]}, "q", multi=False)["results"][0]+def test_a_slimmed_row_still_gets_a_title_from_its_location():+ """The server drops a structural title; the table still shows one."""+ page = {"page_type": "file_page", "path": "a/b.py", "relevance_score": 1.0, "snippet": ""}+ spotlight = {**page, "page_type": "symbol_spotlight", "symbol_id": "a/b.py::f"}+ rows = project({"results": [page, spotlight]}, "q", multi=False)["results"]- assert row["path"].endswith("::resolve_console_width"), "the payload changed shape"- assert row["file"] == "packages/cli/src/repowise/cli/output.py"+ assert [(r["title"], r["path"]) for r in rows] == [("a/b.py", "a/b.py"), ("a/b.py::f", "a/b.py")]+ assert not any("file" in r for r in rows)@pytest.mark.parametrize("hit",[- {**SYMBOL_HIT, "path": "served/sym.py", "file": "old/sym.py"},- {**FILE_HIT, "path": "served/file.py", "file": "old/file.py"},+ {**SYMBOL_HIT, "path": "served/sym.py"},+ {**FILE_HIT, "path": "served/file.py"},{**PAGE_HIT, "path": "served/page.py", "target_path": "old/page.py"},],ids=["symbol", "file", "page"],)def test_every_row_kind_prefers_the_served_path(hit):- """``file`` and ``target_path`` are transition aliases of ``path``."""+ """``target_path`` is a transition alias of ``path``."""row = project({"results": [hit]}, "q", multi=False)["results"][0]assert row["path"].startswith("served/")diff --git a/tests/unit/server/mcp/test_payload_cuts.py b/tests/unit/server/mcp/test_payload_cuts.pyindex 9c004a652..314b866dc 100644--- a/tests/unit/server/mcp/test_payload_cuts.py+++ b/tests/unit/server/mcp/test_payload_cuts.py@@ -22,7 +22,7 @@ from repowise.server.mcp_server.tool_answer.answer import (_trim_served_payload,)from repowise.server.mcp_server.tool_answer.retrieval import _CANDIDATE_LIMIT-from repowise.server.mcp_server.tool_search import _drop_derivable_page_ids+from repowise.server.mcp_server.tool_search import _drop_derivable_page_ids, _slim_served_rows# ---------------------------------------------------------------------------# search_codebase.results[].page_id — derivable from two of its own siblings@@ -225,3 +225,88 @@ def test_truncation_keys_present_when_something_was_dropped():out = truncate_to_budget({"targets": targets, "_meta": {}}, char_budget=2_000)assert out["truncated"] is Trueassert out["dropped_targets"] or out["dropped_symbols"]+++# ---------------------------------------------------------------------------+# search_codebase.results[] — one location per row+# ---------------------------------------------------------------------------+++def _row(page_type, target, title, **extra):+ row = {+ "page_id": f"{page_type}:{target}",+ "page_type": page_type,+ "target_path": target,+ "title": title,+ "sources": ["fts"],+ **extra,+ }+ return row+++def _keyless(monkeypatch, value=False):+ monkeypatch.setattr(+ "repowise.server.mcp_server.tool_search.semantic_search_state", lambda: value+ )+++def test_file_page_row_keeps_only_path(monkeypatch):+ _keyless(monkeypatch)+ (row,) = _slim_served_rows([_row("file_page", "src/a.py", "File: src/a.py")])+ assert row["path"] == "src/a.py"+ assert not {"page_id", "title", "file", "target_path", "sources"} & row.keys()+++def test_symbol_page_row_keeps_path_and_symbol_id(monkeypatch):+ _keyless(monkeypatch)+ row = _row(+ "symbol_spotlight",+ "src/a.py::f",+ "Symbol: src/a.py::f",+ symbol_id="src/a.py::f",+ file="src/a.py",+ )+ row["target_path"] = "src/a.py"+ row["page_id"] = "symbol_spotlight:src/a.py::f"+ (row,) = _slim_served_rows([row])+ assert row["path"] == "src/a.py" and row["symbol_id"] == "src/a.py::f"+ assert not {"page_id", "title", "file"} & row.keys()+++def test_prose_titles_and_unrebuildable_ids_stay(monkeypatch):+ _keyless(monkeypatch)+ module = _row("module_page", "pkg/cmd", "The command layer")+ edited = _row("file_page", "src/b.py", "Why b.py exists")+ unloaded = {"page_id": "file_page:x.py", "page_type": "file_page", "target_path": ""}+ _slim_served_rows([module, edited, unloaded])+ # A module page has no ``path``; its id rebuilds from ``target_path``, which stays.+ assert module["title"] == "The command layer" and module["target_path"] == "pkg/cmd"+ assert edited["title"] == "Why b.py exists" and "page_id" not in edited+ assert unloaded["page_id"] == "file_page:x.py"+++def test_localized_structural_title_is_dropped_per_repo_language(monkeypatch):+ _keyless(monkeypatch)+ de = _row("file_page", "src/a.py", "Datei: src/a.py", repo="de-repo")+ en = _row("file_page", "src/a.py", "File: src/a.py", repo="en-repo")+ wrong = _row("file_page", "src/a.py", "Datei: src/a.py", repo="en-repo")+ _slim_served_rows([de, en, wrong], {"de-repo": "de", "en-repo": "en"})+ assert "title" not in de and "title" not in en+ assert wrong["title"] == "Datei: src/a.py"+++def test_sources_dropped_only_when_fts_only_and_keyless(monkeypatch):+ _keyless(monkeypatch, False)+ fts, sym, both = (+ _row("file_page", "a.py", "A", sources=["fts"]),+ _row("file_page", "b.py", "B", sources=["symbol"]),+ _row("file_page", "c.py", "C", sources=["fts", "vector"]),+ )+ _slim_served_rows([fts, sym, both])+ assert "sources" not in fts+ assert sym["sources"] == ["symbol"] and both["sources"] == ["fts", "vector"]++ for state in (True, None):+ _keyless(monkeypatch, state)+ (kept,) = _slim_served_rows([_row("file_page", "d.py", "D", sources=["fts"])])+ assert kept["sources"] == ["fts"]diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex 9981c2826..f07d6f374 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -732,7 +732,7 @@ class TestSymbolSearch:assert top["symbol_id"] == "src/auth/service.py::AuthService"assert top["name"] == "AuthService"assert top["kind"] == "class"- assert top["file"] == "src/auth/service.py"+ assert top["path"] == "src/auth/service.py"assert top["start_line"] == 10assert top["end_line"] == 100assert top["next"] == "get_symbol"@@ -812,7 +812,7 @@ class TestSymbolSearch:from repowise.server.mcp_server import search_codebaseresult = await search_codebase("AuthService", mode="symbol")- assert not any(r["file"] == "src/auth/service.py" for r in result["results"])+ assert not any(r["path"] == "src/auth/service.py" for r in result["results"])class TestPathSearch:@@ -824,7 +824,7 @@ class TestPathSearch:result = await search_codebase("src/auth/service.py", mode="path")assert result["mode"] == "path"- files = [r["file"] for r in result["results"]]+ files = [r["path"] for r in result["results"]]assert "src/auth/service.py" in filestop = result["results"][0]assert top["type"] == "file"@@ -836,7 +836,7 @@ class TestPathSearch:result = await search_codebase("src/db/models.py")assert result["mode"] == "path"- assert any(r["file"] == "src/db/models.py" for r in result["results"])+ assert any(r["path"] == "src/db/models.py" for r in result["results"])class TestHybridSearch:@@ -1446,9 +1446,9 @@ class TestSearchCandidates:hit = result["results"][0]assert hit["path"] == "api/client.go"assert "target_path" not in hit # same string as path- assert hit["file"] == "api/client.go" # alias for one minor release+ assert hit["path"] == "api/client.go"assert hit["symbol_id"] == "api/client.go::HTTP"- assert hit["file"] == "api/client.go"+ assert hit["path"] == "api/client.go"assert result["candidates"] == [{"path": "api/client.go"}]@pytest.mark.asyncio@@ -1754,7 +1754,7 @@ class TestDistinctFileWindow:await session.commit()res = await search_codebase("widget", mode="hybrid", limit=3)- files = [r["file"] for r in res["results"]]+ files = [r["path"] for r in res["results"]]assert len(files) == 3 and len(set(files)) == 3# The exact name still leads, carrying its same-file sibling.lead = res["results"][0]@@ -1773,7 +1773,7 @@ class TestDistinctFileWindow:assert ids[:2] == ["src/widget/core.py::Box.widget", "src/widget/core.py::widget"]assert all("symbols" not in r for r in res["results"])# Symbol rows serve path, with file as the transition alias.- assert all(r["path"] == r["file"] == "src/widget/core.py" for r in res["results"][:2])+ assert all(r["path"] == "src/widget/core.py" and "file" not in r for r in res["results"][:2])@pytest.mark.asyncioasync def test_concept_window_serves_one_row_per_file(self, setup_mcp):@@ -2036,7 +2036,7 @@ class TestPathModeWithWords:result = await search_codebase("services/_hotkey_pynput.py register hotkey", mode="path")- assert [r["file"] for r in result["results"]] == ["services/_hotkey_pynput.py"]+ assert [r["path"] for r in result["results"]] == ["services/_hotkey_pynput.py"]class TestSymbolModeExactOnly:diff --git a/tests/unit/server/mcp/test_search_candidates.py b/tests/unit/server/mcp/test_search_candidates.pyindex caf5cb476..271d537de 100644--- a/tests/unit/server/mcp/test_search_candidates.py+++ b/tests/unit/server/mcp/test_search_candidates.py@@ -92,10 +92,13 @@ class TestAddRowPaths:unloaded = _page("file_page", "")add_row_paths([symbol, file_row, file_page, spotlight, module, unloaded])- assert symbol["path"] == symbol["file"] == "a.py"- assert file_row["path"] == file_row["file"] == "b.py"+ assert symbol["path"] == "a.py"+ assert "file" not in symbol+ assert file_row["path"] == "b.py"+ assert "file" not in file_rowassert file_page == {"page_type": "file_page", "path": "c.py"}- assert spotlight["path"] == spotlight["file"] == "d.py"+ assert spotlight["path"] == "d.py"+ assert "file" not in spotlightassert "target_path" not in spotlight# Pathless rows keep their key in target_path and get no path.assert module == _page("module_page", "pkg/cmd")diff --git a/tests/unit/sessions/test_codex_adapter.py b/tests/unit/sessions/test_codex_adapter.pyindex 39e4d216b..884a7922b 100644--- a/tests/unit/sessions/test_codex_adapter.py+++ b/tests/unit/sessions/test_codex_adapter.py@@ -185,7 +185,7 @@ def test_normalize_handles_mcp_function_call_and_output(adapter: CodexAdapter) -"output": ('Wall time: 0.1 seconds\n''Output:\n'- '{"result":{"results":[{"file":"app.py"}]}}'+ '{"result":{"results":[{"path":"app.py"}]}}'),},}@@ -317,7 +317,7 @@ def test_a_content_match_binds_the_path_not_the_matched_line(adapter: CodexAdaptassert event is not Noneresults = json.loads(event.tool_results[0].content)["result"]["results"]- assert results == [{"path": "src/app.py", "file": "src/app.py"}]+ assert results == [{"path": "src/app.py"}]def test_a_root_level_content_match_still_binds_its_path(adapter: CodexAdapter) -> None:@@ -331,7 +331,7 @@ def test_a_root_level_content_match_still_binds_its_path(adapter: CodexAdapter)assert event is not Noneresults = json.loads(event.tool_results[0].content)["result"]["results"]- assert results == [{"path": "app.py", "file": "app.py"}]+ assert results == [{"path": "app.py"}]assert call_event is not Noneassert call_event.tool_uses[0].input["path"] == "app.py"@@ -343,7 +343,7 @@ def test_a_bare_root_level_filename_is_kept(adapter: CodexAdapter) -> None:assert event is not Noneresults = json.loads(event.tool_results[0].content)["result"]["results"]- assert results == [{"path": "setup.py", "file": "setup.py"}]+ assert results == [{"path": "setup.py"}]def test_a_bare_prose_line_is_still_dropped(adapter: CodexAdapter) -> None:diff --git a/tests/unit/sessions/test_demand_miner.py b/tests/unit/sessions/test_demand_miner.pyindex fdd771a3a..2a18a0644 100644--- a/tests/unit/sessions/test_demand_miner.py+++ b/tests/unit/sessions/test_demand_miner.py@@ -106,7 +106,7 @@ def test_get_answer_dedups_and_caps_per_call():def test_search_attributes_to_hit_files_and_symbols():payload = {"results": [- {"file": "pkg/a.py"},+ {"path": "pkg/a.py"},{"target_path": "pkg/b.py"},{"symbol_id": "pkg/c.py::Thing"},]@@ -117,10 +117,10 @@ def test_search_attributes_to_hit_files_and_symbols():def test_search_prefers_the_served_path():- # ``file`` and ``target_path`` are aliases; ``path`` is the openable file.+ # ``target_path`` is an alias; ``path`` is the openable file.payload = {"results": [- {"path": "pkg/a.py", "file": "pkg/old.py"},+ {"path": "pkg/a.py", "target_path": "pkg/old.py"},{"path": "pkg/b.py", "target_path": "pkg/other.py"},]}@@ -134,7 +134,7 @@ def test_two_calls_accumulate():_answer_call("a1"),_result("a1", {"citations": ["pkg/a.py"]}),_search_call("s1"),- _result("s1", {"results": [{"file": "pkg/a.py"}]}),+ _result("s1", {"results": [{"path": "pkg/a.py"}]}),]demand = mine_events_demand(events, REPO_PREFIX)assert demand == {"pkg/a.py": 2}