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(graph): resolve a namespace member through the re-export chain (#1672)
Raghav Chamadiya7095cccb0a94
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex ffa4165df..aadb18146 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -286,6 +286,7 @@ class CallResolver:# "*" name (it is not a binding), so without this pass the barrel chain# dead-ends one hop short of the real definition and a call through the# barrel resolves to nothing.+ wildcard_sources: dict[str, list[str]] = defaultdict(list)for path, parsed in self._parsed_files.items():file_syms = self._file_symbols.get(path, {})for imp in parsed.imports:@@ -294,12 +295,56 @@ class CallResolver:continueif imp.resolved_file.startswith("external:"):continue+ # ``export * as ns from "x"`` forwards the module under ``ns``,+ # so x's names are reachable as ``ns.name`` and are NOT this+ # file's own exports. Flattening them makes a bare ``name``+ # resolve into a nested namespace it was never in.+ if any(+ b.local_name == "*" and b.exported_name for b in imp.bindings+ ):+ continueresolved = imp.resolved_file+ if resolved != path:+ wildcard_sources[path].append(resolved)source_syms = self._file_symbols.get(resolved, {})for sym_name in source_syms:if sym_name not in file_syms:self._barrel_origins[path][sym_name] = resolved+ # The pass above forwards only what the source file DECLARES, so a+ # barrel over a barrel forwards nothing and the chain breaks at its+ # first link rather than its last. Forward what the source file+ # re-exports too, to a fixpoint. The multi-hop pass below cannot do+ # this job — it deepens entries that exist, and here none do.+ #+ # Sorted so that a name two of this file's barrels both forward lands on+ # the same origin whatever order the repository was walked in.+ for _ in range(4):+ changed = False+ for path, sources in sorted(wildcard_sources.items()):+ file_syms = self._file_symbols.get(path, {})+ origins = self._barrel_origins[path]+ for source in sorted(sources):+ source_bindings = self._import_bindings.get(source, {})+ for name, declaring in sorted(self._barrel_origins.get(source, {}).items()):+ if name in file_syms or name in origins or declaring == path:+ continue+ # The map keys a name as the source file spells it and+ # records only the declaring file, never the name the+ # symbol has there. A hop that renames therefore hands+ # on a key the declaring file may coincidentally+ # declare as something unrelated, and the receiving+ # file carries no binding to undo it with. Refuse those+ # rather than forward a name that means something else+ # at the far end; it costs reach, never correctness.+ binding = source_bindings.get(name)+ if binding is not None and (binding.exported_name or name) != name:+ continue+ origins[name] = declaring+ changed = True+ if not changed:+ break+# Multi-hop: follow chains up to 5 hopsfor _ in range(4):changed = False@@ -888,6 +933,24 @@ class CallResolver:return ResolvedCall(caller_id, source_syms[method_name], 0.88, call.line, "module_alias")+ # A namespace over a barrel names a file that declares nothing of+ # its own, so the lookup above can only ever miss. Chase the+ # re-export map, as free calls and typed receivers already do.+ #+ # Keyed on the name the declaring file uses, not the one written+ # here: a member access cannot rename, but the re-export it arrives+ # through can, and the map records only the file. Without this an+ # ``export { foo as bar }`` binds any unrelated ``bar`` the+ # declaring file happens to hold.+ origin = self._barrel_origins.get(module_file, {}).get(method_name)+ if origin is not None and origin != module_file:+ binding = self._import_bindings.get(module_file, {}).get(method_name)+ declared_name = (binding.exported_name if binding else None) or method_name+ origin_syms = self._file_symbols.get(origin, {})+ if declared_name in origin_syms:+ return ResolvedCall(+ caller_id, origin_syms[declared_name], 0.88, call.line, "module_alias"+ )# Strategy 1b: receiver in import names (non-alias fallback for backward compat)name_to_file = self._import_names.get(file_path, {})diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.pyindex c84206de2..221a131fd 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py@@ -108,10 +108,19 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[N))elif child.type == "namespace_export":- # ``export * as ns from "x"`` — forwards the whole module.+ # ``export * as ns from "x"`` — forwards the whole module, but+ # under ``ns`` rather than flattened into this file's own+ # namespace. The name rides on the wildcard binding so a+ # consumer can tell the two shapes apart; the import-name maps+ # drop a ``"*"`` binding before reading either field, so no+ # lookup changes and ``imported_names`` stays as it was.+ ns_name = next(+ (node_text(c, src) for c in child.children if c.type == "identifier"),+ None,+ )names.append("*")bindings.append(- NamedBinding(local_name="*", exported_name=None, source_file=None)+ NamedBinding(local_name="*", exported_name=ns_name, source_file=None))continuediff --git a/tests/unit/ingestion/test_star_import_barrel.py b/tests/unit/ingestion/test_star_import_barrel.pyindex f78e4ce54..77cb51599 100644--- a/tests/unit/ingestion/test_star_import_barrel.py+++ b/tests/unit/ingestion/test_star_import_barrel.py@@ -54,6 +54,107 @@ def test_call_through_star_import_barrel_resolves(tmp_path: Path) -> None:assert ("caller.py::run", "other.py::Thing::helper") not in edges, edges+def test_namespace_member_resolves_through_a_barrel(tmp_path: Path) -> None:+ """``import * as ns`` binds the barrel, which declares nothing itself.++ The member lookup can only ever miss there, so the re-export map has to be+ chased for the member name too.+ """+ files = {+ "leaf.ts": "export function helper(x: number) {\n return x;\n}\n",+ "barrel.ts": 'export * from "./leaf.js";\n',+ # a second `helper` defeats the global-unique tier+ "other.ts": "export class Thing {\n helper(x: number) {\n return x;\n }\n}\n",+ "caller.ts": (+ 'import * as ns from "./barrel.js";\n\nexport function run() {\n return ns.helper(1);\n}\n'+ ),+ }+ edges = _build_calls(tmp_path, files)+ assert ("caller.ts::run", "leaf.ts::helper") in edges, edges+ assert ("caller.ts::run", "other.ts::Thing::helper") not in edges, edges+++def test_namespace_member_resolves_through_a_barrel_over_a_barrel(tmp_path: Path) -> None:+ """Each hop forwards only what its source declares, so a chain of+ re-exporting files breaks at its first link unless what a source itself+ re-exports is forwarded too."""+ files = {+ "leaf.ts": "export function helper(x: number) {\n return x;\n}\n",+ "inner.ts": 'export * from "./leaf.js";\n',+ "outer.ts": 'export * from "./inner.js";\n',+ "other.ts": "export class Thing {\n helper(x: number) {\n return x;\n }\n}\n",+ "caller.ts": (+ 'import * as ns from "./outer.js";\n\nexport function run() {\n return ns.helper(1);\n}\n'+ ),+ }+ edges = _build_calls(tmp_path, files)+ assert ("caller.ts::run", "leaf.ts::helper") in edges, edges+ assert ("caller.ts::run", "other.ts::Thing::helper") not in edges, edges+++def test_a_nested_namespace_reexport_is_not_flattened(tmp_path: Path) -> None:+ """``export * as coerce from "./coerce.js"`` puts coerce's names under+ ``coerce``, not at top level, so a bare ``ns.string()`` must take the+ top-level declaration and never the nested one."""+ files = {+ "coerce.ts": "export function string(x: unknown) {\n return String(x);\n}\n",+ "schemas.ts": "export function string(y: number) {\n return y;\n}\n",+ "external.ts": (+ 'export * as coerce from "./coerce.js";\nexport * from "./schemas.js";\n'+ ),+ "caller.ts": (+ 'import * as z from "./external.js";\n\nexport function run() {\n return z.string(1);\n}\n'+ ),+ }+ edges = _build_calls(tmp_path, files)+ assert ("caller.ts::run", "coerce.ts::string") not in edges, edges+ assert ("caller.ts::run", "schemas.ts::string") in edges, edges+++def test_namespace_member_through_a_renaming_reexport_takes_the_renamed_symbol(+ tmp_path: Path,+) -> None:+ """``export { foo as bar }`` must bind ``foo``, not a same-named stranger.++ The re-export map records only the declaring file, so the name written at+ the call site is not the name that file declares.+ """+ files = {+ "leaf.ts": (+ "export function foo(x: number) {\n return x;\n}\n"+ "export function bar(y: string) {\n return y;\n}\n"+ ),+ "mid.ts": 'export { foo as bar } from "./leaf.js";\n',+ "caller.ts": (+ 'import * as ns from "./mid.js";\n\nexport function run() {\n return ns.bar(1);\n}\n'+ ),+ }+ edges = _build_calls(tmp_path, files)+ assert ("caller.ts::run", "leaf.ts::bar") not in edges, edges+ assert ("caller.ts::run", "leaf.ts::foo") in edges, edges+++def test_namespace_member_refuses_a_rename_forwarded_across_a_wildcard(+ tmp_path: Path,+) -> None:+ """A wildcard hop hands on the renamed spelling and no binding to undo it+ with, so the name is refused rather than bound to whatever the declaring+ file happens to call ``bar``."""+ files = {+ "leaf.ts": (+ "export function foo(x: number) {\n return x;\n}\n"+ "export function bar(y: string) {\n return y;\n}\n"+ ),+ "mid1.ts": 'export { foo as bar } from "./leaf.js";\n',+ "mid2.ts": 'export * from "./mid1.js";\n',+ "caller.ts": (+ 'import * as ns from "./mid2.js";\n\nexport function run() {\n return ns.bar(1);\n}\n'+ ),+ }+ edges = _build_calls(tmp_path, files)+ assert ("caller.ts::run", "leaf.ts::bar") not in edges, edges++def test_star_barrel_edge_survives_global_name_shadow(tmp_path: Path) -> None:"""A same-named method elsewhere makes the name globally non-unique, so theTier-3 fallback cannot resolve the call: only following the star re-export