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(graph): a type imported from an external package never resolves to a repo file by name (#3527)
Raghav Chamadiya3315bba28e7a
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex 8a5a5d02b..e43fad782 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -160,6 +160,17 @@ def _names_only_own_types(data: dict[str, Any], own: set[str]) -> bool:return bool(names) and own.issuperset(names)+# Language families a type name can resolve into by file name. A stem match+# outside the family is a coincidence of names, never a definition.+_TS_TYPE_LANGUAGES: frozenset[str] = frozenset({"typescript", "javascript", "vue", "svelte"})+_C_TYPE_LANGUAGES: frozenset[str] = frozenset({"c", "cpp"})+++def _node_language_in(graph: nx.DiGraph, node: str, languages: frozenset[str]) -> bool:+ """Whether *node* is a graph file written in one of *languages*."""+ return graph.has_node(node) and graph.nodes[node].get("language") in languages++# ---------------------------------------------------------------------------# Strategy: C# / .NET# ---------------------------------------------------------------------------@@ -595,8 +606,13 @@ def _find_c_type_file(if type_name in defined_names.get(sib, _EMPTY_NAMES):return sib+ # Same language family only: the stem map spans every language.candidates = ctx.stem_map.get(type_name.lower(), [])- if len(candidates) == 1 and candidates[0] != from_path and graph.has_node(candidates[0]):+ if (+ len(candidates) == 1+ and candidates[0] != from_path+ and _node_language_in(graph, candidates[0], _C_TYPE_LANGUAGES)+ ):return candidates[0]return None@@ -623,8 +639,9 @@ def _resolve_ts_type_refs(``resolved_file`` is the answer.2. ``import * as ns from './x'`` — ``ns.Foo`` strips to ``Foo``;the namespace alias points at the module.- 3. Stem-map fallback — unique global file whose- basename matches the type name; matches Rust's strategy.+ 3. Stem-map fallback — unique global TS/JS file whose+ basename matches the type name; matches Rust's strategy. A name+ bound by a package import never reaches this step.4. Same-file definitions are skipped silently (no edge needed).This emits ``type_use`` edges at file granularity — the dead-code@@ -641,8 +658,15 @@ def _resolve_ts_type_refs(name_to_source: dict[str, str] = {}# alias -> resolved_file for namespace / module imports.namespace_to_source: dict[str, str] = {}+ # Names bound by a package import (``import { type Dispatch } from+ # "react"``). Their definition is outside the repo, so a repo file with a+ # matching name is never the answer.+ external_names: set[str] = set()for imp in parsed.imports:- if not imp.resolved_file or imp.resolved_file.startswith("external:"):+ if not imp.resolved_file:+ continue+ if imp.resolved_file.startswith("external:"):+ external_names.update(b.local_name for b in imp.bindings)continuefor binding in imp.bindings:if binding.local_name == "*":@@ -674,6 +698,8 @@ def _resolve_ts_type_refs(same_file_refs.add(name)continuetarget = name_to_source.get(name) or namespace_to_source.get(name)+ if target is None and name in external_names:+ continueif target is None:target = _find_unique_ambient_declaration(name, from_path, graph, defined_names, ctx@@ -789,6 +815,10 @@ def _find_ts_type_in_stem_map(candidate = candidates[0]if candidate == from_path:return None+ # The stem map spans every language: ``React.Dispatch`` matched a Python+ # ``dispatch.py`` that defines a ``Dispatch`` class.+ if not _node_language_in(graph, candidate, _TS_TYPE_LANGUAGES):+ return None# Verify the candidate file actually exports a symbol matching name —# avoids accidentally matching ``utils.ts`` to a type called ``Utils``.if type_name in defined_names.get(candidate, _EMPTY_NAMES):diff --git a/tests/unit/ingestion/test_ts_type_use.py b/tests/unit/ingestion/test_ts_type_use.pyindex 52bcd509a..c1aa6217a 100644--- a/tests/unit/ingestion/test_ts_type_use.py+++ b/tests/unit/ingestion/test_ts_type_use.py@@ -234,6 +234,40 @@ class TestTsTypeUseEdges:assert edge and "AmbientSettings" in edge["type_uses"]assert "ModuleOnly" not in edge["type_uses"]+ def test_package_import_never_resolves_to_a_repo_file_by_name(+ self, tmp_path: Path+ ) -> None:+ graph = _build_graph(+ tmp_path,+ {+ "dispatch.ts": "export interface Dispatch { run(): void }\n",+ "hook.ts": (+ 'import { type Dispatch } from "react"\n'+ "export function use(set: Dispatch): void {}\n"+ ),+ },+ )+ assert not graph.has_edge("hook.ts", "dispatch.ts")++ def test_stem_match_never_crosses_languages(self, tmp_path: Path) -> None:+ sources = {+ "py/dispatch.py": "class Dispatch:\n pass\n",+ "hook.ts": (+ 'import * as React from "react"\n'+ "export function use(set: React.Dispatch): void {}\n"+ ),+ }+ for rel, body in sources.items():+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text(body, encoding="utf-8")+ builder = GraphBuilder(repo_path=tmp_path)+ for rel, lang in (("py/dispatch.py", "python"), ("hook.ts", "typescript")):+ path = tmp_path / rel+ builder.add_file(+ _PARSER.parse_file(_file_info(rel, str(path.resolve()), lang), path.read_bytes())+ )+ assert not builder.build().has_edge("hook.ts", "py/dispatch.py")+def test_type_only_import_produces_type_use_provenance(self, tmp_path: Path) -> None: