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
fix(context): follow a local import alias in the references edit set (#3190)
Raghav Chamadiya8fa62dacb462
diff --git a/packages/server/src/repowise/server/mcp_server/_edit_sites.py b/packages/server/src/repowise/server/mcp_server/_edit_sites.pyindex d082cde41..253fb7ef9 100644--- a/packages/server/src/repowise/server/mcp_server/_edit_sites.py+++ b/packages/server/src/repowise/server/mcp_server/_edit_sites.py@@ -52,25 +52,37 @@ _IMPORT_START = re.compile(r"^\s*(?:from\s+\S+\s+import\b|import\b|export\s.*\bfrom\b|export\s*\{|using\b|use\b"r"|#\s*include\b|(?:const|let|var)\s.*\brequire\s*\()")+# A statement that can hand a local name to other files: export lists, default+# exports, CommonJS export assignments and Python ``__all__``.+_EXPORT_START = re.compile(+ r"^\s*(?:export\s*(?:\{|\*|default\b)|(?:module\.)?exports\b|__all__\b)"+)+_CJS_EXPORT = re.compile(r"\bmodule\.exports\b|(?<![\w$.])exports\.")+_EXPORT_LINE = re.compile(r"^\s*export\b")+_CALL_AFTER = re.compile(r"\s*(?:\?\.)?\(")+# Uses of a name that cannot hand its binding on: a call, a member access,+# ``new name`` and a JSX tag.+_LOCAL_USE_AFTER = re.compile(r"\s*(?:\(|\?\.|\.(?!\.))")+_LOCAL_USE_BEFORE = re.compile(r"(?:\bnew\s+|</?)$")def _bare_name(node: GraphNode) -> str:return id_segment_name((node.name or node.node_id).split("::")[-1].split(".")[-1])-def _import_lines(lines: list[str]) -> set[int]:- """1-based line numbers that belong to an import statement."""+def _import_lines(lines: list[str], start: re.Pattern[str] = _IMPORT_START) -> set[int]:+ """1-based line numbers that belong to a statement opening with *start*."""out: set[int] = set()i = 0while i < len(lines):- if not _IMPORT_START.match(lines[i]):+ if not start.match(lines[i]):i += 1continuedepth = 0while i < len(lines):text = lines[i]out.add(i + 1)- depth += text.count("(") + text.count("{") - text.count(")") - text.count("}")+ depth += sum(text.count(c) for c in "({[") - sum(text.count(c) for c in ")}]")i += 1if depth <= 0 and not text.rstrip().endswith("\\"):break@@ -97,8 +109,9 @@ def _scan(name: str,definition: tuple[str, int, int],call_lines: dict[str, set[int]],-) -> tuple[list[dict[str, Any]], list[str], int, set[str], bool]:- """``(sites, unreadable, stale call lines, files renaming it, default-exported)``."""+) -> tuple[list[dict[str, Any]], list[str], int, set[str], bool, dict[str, set[str]]]:+ """``(sites, unreadable, stale call lines, files renaming it, default-exported,+ local import aliases per Python file)``."""esc = re.escape(name)word = re.compile(rf"(?<![\w$]){esc}(?![\w$])")as_rename = re.compile(rf"(?<![\w$.]){esc}\s+as\s+([\w$]+)")@@ -108,12 +121,12 @@ def _scan(ternary = re.compile(rf"\?[^:]*(?<![\w$]){esc}\s*:")# Bound under any name by its importers, so no spelling can be scanned for.default_export = re.compile(r"\bexport\s+default\b|\bas\s+default\b")- cjs_export = re.compile(r"\bmodule\.exports\b|(?<![\w$.])exports\.")def_path, def_start, def_end = definitionsites: list[dict[str, Any]] = []unreadable: list[str] = []stale = 0renamed: set[str] = set()+ python_aliases: dict[str, set[str]] = {}is_default = Falsefor rel in files:lines = _read_lines(root, rel)@@ -123,20 +136,27 @@ def _scan(imports = _import_lines(lines)python = Path(rel).suffix in _PYTHON_EXTENSIONSaliases: set[str] = set()+ # Aliases bound by an import; a rename anywhere else is always a hole.+ imported: set[str] = set()for n, text in enumerate(lines, 1):if not word.search(text):continue- if n in imports:- aliases.update(m.group(1) for m in as_rename.finditer(text))+ found = [m.group(1) for m in as_rename.finditer(text)] if n in imports else []if not python and not ternary.search(text):- aliases.update(m.group(1) for m in colon_rename.finditer(text))+ found += [m.group(1) for m in colon_rename.finditer(text)]+ aliases.update(found)+ if n in imports:+ imported.update(found)# ``name as default`` is the default-export case below, not a rename.aliases.discard("default")- if aliases:+ local = aliases & imported+ if aliases - imported or _aliases_leave(rel, lines, local, imports):renamed.add(rel)+ elif python and local:+ python_aliases[rel] = localif rel == def_path and not python:# A CommonJS module's exports can rename on any line, so any use counts.- commonjs = any(cjs_export.search(t) for t in lines)+ commonjs = any(_CJS_EXPORT.search(t) for t in lines)if commonjs or any(default_export.search(t) and word.search(t) for t in lines):is_default = Truespellings = [word] + [re.compile(rf"(?<![\w$]){re.escape(a)}(?![\w$])") for a in aliases]@@ -158,7 +178,39 @@ def _scan(else:kind = "reference"sites.append({"path": rel, "line": n, "kind": kind, "text": text.strip()[:MAX_TEXT_CHARS]})- return sites, unreadable, stale, renamed, is_default+ return sites, unreadable, stale, renamed, is_default, python_aliases+++def _aliases_leave(rel: str, lines: list[str], aliases: set[str], imports: set[int]) -> bool:+ """True unless every use of an import alias in *rel* is one that cannot hand it on.++ Only a call, ``new``, a JSX tag or a member access counts as local; any+ value use (argument, assignment, export, ``extends``) may pass the binding+ to another file. A plain Python module's alias is also checked against its+ importers by the caller.+ """+ if not aliases:+ return False+ if Path(rel).name == "__init__.py":+ return True+ exports = _import_lines(lines, _EXPORT_START)+ alt = "|".join(re.escape(a) for a in sorted(aliases))+ spelled = re.compile(rf"(?<![\w$])(?:{alt})(?![\w$])")+ for n, text in enumerate(lines, 1):+ if n in imports and n not in exports:+ continue+ # On an export line only a call stays local: ``b.bind(null)`` hands on a copy.+ handed = n in exports or _EXPORT_LINE.match(text) or _CJS_EXPORT.search(text)+ for m in spelled.finditer(text):+ if handed:+ if not _CALL_AFTER.match(text, m.end()):+ return True+ elif not (+ _LOCAL_USE_AFTER.match(text, m.end())+ or _LOCAL_USE_BEFORE.search(text, 0, m.start())+ ):+ return True+ return Falsedef _cap_references_per_file(sites: list[dict[str, Any]]) -> list[dict[str, Any]]:@@ -296,9 +348,23 @@ async def reference_edit_set(ordered = ordered[:MAX_FILES]unindexed = unindexed[: max(0, MAX_FILES - len(ordered))]definition = (def_file, node.start_line or 0, node.end_line or node.start_line or 0)- sites, unreadable, stale, renamed_in, is_default = await asyncio.to_thread(+ sites, unreadable, stale, renamed_in, is_default, python_aliases = await asyncio.to_thread(_scan, root, ordered + unindexed, name, definition, call_lines)+ if python_aliases:+ # Any module-level Python name is importable, so an alias another file+ # imports (or may, by unknown names or ``*``) leaves its file.+ rows = await session.execute(+ select(GraphEdge.target_node_id, GraphEdge.imported_names_json).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.edge_type == "imports",+ GraphEdge.target_node_id.in_(list(python_aliases)),+ )+ )+ for tgt, names_json in rows.all():+ names = _names(names_json)+ if not names or "*" in names or python_aliases[tgt] & set(names):+ renamed_in.add(tgt)unindexed_set = set(unindexed)if unreadable:diff --git a/tests/unit/server/mcp/test_context_references.py b/tests/unit/server/mcp/test_context_references.pyindex 64291b529..0ca76c1d3 100644--- a/tests/unit/server/mcp/test_context_references.py+++ b/tests/unit/server/mcp/test_context_references.py@@ -322,8 +322,10 @@ async def test_default_export_is_incomplete(session, repo_id, tmp_path):@pytest.mark.asyncio-async def test_commonjs_destructure_rename_is_incomplete(session, repo_id, tmp_path):- """Both the one-line and the multi-line ``{ pick: other } = require(...)``."""+async def test_commonjs_destructure_rename_outside_an_import_line_is_incomplete(+ session, repo_id, tmp_path+):+ """A one-line ``{ pick: other } = require(...)`` is an import; a multi-line one is not seen as one."""node = await _seed_js(session,repo_id,@@ -342,7 +344,7 @@ async def test_commonjs_destructure_rename_is_incomplete(session, repo_id, tmp_passert ("web/multi.js", 4, "reference") in sitesassert out["complete"] is Falserenamed = next(r for r in out["reasons"] if r.startswith("renamed on import or export"))- assert "web/one.js" in renamed and "web/multi.js" in renamed+ assert "web/one.js" not in renamed and "web/multi.js" in renamed@pytest.mark.asyncio@@ -367,6 +369,189 @@ async def test_rename_in_a_file_outside_the_re_export_chain_is_incomplete(assert any("web/c.ts" in r for r in out["reasons"])+_PICK = "export function pick(x: number) { return x }\n"+++ ("rel", "text", "alias_line"),+ [+ ("web/b.ts", "import { pick as choose } from './a'\n\nexport const f = () => choose(1)\n", 3),+ (+ "web/b.ts",+ "import {\n other,\n pick as choose,\n} from './a'\nfunction f() {\n return choose(1)\n}\n",+ 6,+ ),+ ("web/b.js", "const { pick: choose } = require('./a')\nchoose(1)\n", 2),+ ("web/b.ts", "import { pick as choose } from './a'\nconst k = new choose()\n", 2),+ ("web/b.tsx", "import { pick as choose } from './a'\nconst e = <choose a={1}></choose>\n", 2),+ ("web/b.ts", "import { pick as choose } from './a'\nchoose.mockReset()\n", 2),+ ("web/b.ts", "import { pick as choose } from './a'\nconst n = choose?.length\n", 2),+ ],+)+async def test_import_alias_used_only_locally_is_complete(+ session, repo_id, tmp_path, rel, text, alias_line+):+ node = await _seed_js(session, repo_id, tmp_path, {"web/a.ts": _PICK, rel: text})++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ assert (rel, alias_line, "reference") in _sites(out)+ assert out["complete"] is True, out.get("reasons")+++ "text",+ [+ "import { pick as choose } from './a'\nexport { choose }\n",+ "import { pick as choose } from './a'\nexport {\n choose as chooser,\n}\n",+ "import { pick as choose } from './a'\nexport default choose\n",+ "import { pick as choose } from './a'\nexport const chooser = choose;\n",+ "export { pick as choose } from './a'\n",+ "const { pick: choose } = require('./a')\nmodule.exports = {\n choose,\n}\n",+ "const { pick: choose } = require('./a')\nexports.chooser = choose\n",+ "import { pick as choose } from './a'\nexport = choose;\n",+ "import { pick as choose } from './a'\nexport const api = { choose }\n",+ "import { pick as choose } from './a'\nexport const api = {\n choose,\n}\n",+ "import { pick as choose } from './a'\nexport const w = wrap(choose)\n",+ "import { pick as choose } from './a'\nexport const a = choose as T\n",+ "import { pick as choose } from './a'\nexport const a = choose, c = 1\n",+ "import { pick as choose } from './a'\nconst c = choose\nexport { c }\n",+ "import { pick as choose } from './a'\nconst c = choose\nexport default c\n",+ "const { pick: choose } = require('./a')\no.x = choose\nmodule.exports = o\n",+ "import { pick as choose } from './a'\nexport class K extends choose {}\n",+ "import { pick as choose } from './a'\nexport function g() { return choose }\n",+ ],+)+async def test_import_alias_handed_on_is_incomplete(session, repo_id, tmp_path, text):+ node = await _seed_js(session, repo_id, tmp_path, {"web/a.ts": _PICK, "web/b.js": text})++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ assert out["complete"] is False+ assert "renamed on import or export: web/b.js" in out["reasons"]+++async def test_aliases_in_two_files_are_both_scanned(session, repo_id, tmp_path):+ node = await _seed_js(+ session,+ repo_id,+ tmp_path,+ {+ "web/a.ts": _PICK,+ "web/b.ts": "import { pick as choose } from './a'\nchoose(1)\n",+ "web/c.ts": "import { pick as select } from './a'\nconst v = select(2)\n",+ },+ )++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ assert ("web/b.ts", 2, "reference") in _sites(out)+ assert ("web/c.ts", 2, "reference") in _sites(out)+ assert out["complete"] is True, out.get("reasons")+++async def test_alias_matches_on_a_word_boundary_only(session, repo_id, tmp_path):+ node = await _seed_js(+ session,+ repo_id,+ tmp_path,+ {+ "web/a.ts": _PICK,+ "web/b.ts": (+ "import { pick as choose } from './a'\n"+ "const chooser = 1\n"+ "obj.choose_it = $choose\n"+ "choose(chooser)\n"+ ),+ },+ )++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ b_lines = [n for p, n, _k in _sites(out) if p == "web/b.ts"]+ assert b_lines == [1, 4]+ assert out["complete"] is True, out.get("reasons")+++ ("importer_names", "complete"),+ [(None, True), ('["value"]', True), ('["pick_backend"]', False), ("[]", False)],+)+async def test_python_module_alias_is_local_unless_another_module_imports_it(+ session, repo_id, tmp_path, importer_names, complete+):+ extra = [("app/local.py", _DEF, "imports", {"imported_names_json": '["backend_of"]'})]+ if importer_names is not None:+ extra.append(+ ("app/far.py", "app/local.py", "imports", {"imported_names_json": importer_names})+ )+ node = await _seed(session, repo_id, tmp_path, extra=extra)+ (tmp_path / "app" / "local.py").write_text(+ "from pkg.catalog import backend_of as pick_backend\n\nvalue = pick_backend(1)\n",+ encoding="utf-8",+ )++ (tmp_path / "app" / "far.py").write_text(+ "from app.local import pick_backend, value\n", encoding="utf-8"+ )++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ assert ("app/local.py", 1, "import") in _sites(out)+ assert ("app/local.py", 3, "reference") in _sites(out)+ assert out["complete"] is complete, out.get("reasons")+ if not complete:+ assert "renamed on import or export: app/local.py" in out["reasons"]+++ ("body", "complete"),+ [+ ("__all__ = [\n 'pick_backend',\n]\n", False),+ ("chooser = pick_backend\n", False),+ ("register(pick_backend)\n", False),+ ("value = pick_backend(1)\nname = pick_backend.__name__\n", True),+ ],+)+async def test_python_alias_value_use_leaves_the_file(session, repo_id, tmp_path, body, complete):+ node = await _seed(+ session,+ repo_id,+ tmp_path,+ extra=[("app/api.py", _DEF, "imports", {"imported_names_json": '["backend_of"]'})],+ )+ (tmp_path / "app" / "api.py").write_text(+ "from pkg.catalog import backend_of as pick_backend\n\n" + body, encoding="utf-8"+ )++ out = await reference_edit_set(session, repo_id, tmp_path, node)++ assert out["complete"] is complete, out.get("reasons")+ if not complete:+ assert "renamed on import or export: app/api.py" in out["reasons"]+++async def test_local_alias_references_share_the_per_file_cap(session, repo_id, tmp_path):+ spec = "import { pick as choose } from './a'\n" + "choose.mockReturnValue(1)\n" * 10+ node = await _seed_js(+ session, repo_id, tmp_path, {"web/a.ts": _PICK, "web/a.test.ts": spec}+ )++ out = await reference_edit_set(session, repo_id, tmp_path, node, _collector(tmp_path))++ assert out["sites_omitted_by_file"] == {+ "web/a.test.ts": 10 - _edit_sites.MAX_REFERENCES_PER_FILE+ }+ assert not any(r.startswith("renamed") for r in out["reasons"])++@pytest.mark.asyncioasync def test_get_context_serves_references_for_a_symbol(setup_mcp, session, tmp_path):from repowise.server.mcp_server import get_context@@ -498,3 +683,16 @@ async def test_get_context_collapses_a_flood_into_recoverable_counts(setup_mcp,assert (_USER, 9, "call") in _sites(refs)assert refs["complete"] is Falseassert resp["_meta"]["omitted"]["refs"]+++ "line",+ [+ "export const g = choose.bind(null);",+ "export const f = choose.call;",+ "module.exports.x = choose.y;",+ ],+)+def test_alias_member_access_on_an_export_line_is_incomplete(line: str) -> None:+ lines = ['import { pick as choose } from "./d";', line]+ assert _edit_sites._aliases_leave("u.ts", lines, {"choose"}, {1})