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(ingestion): constrain chained C++ calls by return type (#1782)
Raghav Chamadiya44d0a9a05feb
diff --git a/packages/core/src/repowise/core/ingestion/__init__.py b/packages/core/src/repowise/core/ingestion/__init__.pyindex 08321f951..375d79f70 100644--- a/packages/core/src/repowise/core/ingestion/__init__.py+++ b/packages/core/src/repowise/core/ingestion/__init__.py@@ -14,6 +14,7 @@ from .change_detector import AffectedPages, ChangeDetector, FileDiff, SymbolDifffrom .graph import GraphBuilderfrom .models import (EXTENSION_TO_LANGUAGE,+ CallReceiver,CallSite,EdgeType,FileInfo,@@ -39,6 +40,7 @@ __all__ = [# Change detection"AffectedPages",# Models+ "CallReceiver","CallSite","ChangeDetector","EdgeType",diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 259f79dfe..41989c9c2 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -51,6 +51,7 @@ from .models import (ResolutionOrigin,symbol_id_language,)+from .return_types import declared_return_type, normalize_return_type, signature_parameter_countlog = structlog.get_logger(__name__)@@ -164,6 +165,10 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {_SOURCE_CACHE_FILES = 4_BODY_TYPE_CACHE_ENTRIES = 2048+# Phase admission is intentionally explicit. P16 lands the behavior-preserving+# substrate with no language enabled; later phases add only measured lanes.+PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES: frozenset[str] = frozenset({"cpp"})+@dataclass(frozen=True, slots=True)class ResolvedCall:@@ -197,11 +202,17 @@ class CallResolver:repo_path: str | None = None,import_maps: Any | None = None,heritage_parents: dict[str, set[str]] | None = None,+ return_type_chain_languages: frozenset[str] | None = None,) -> None:# {type symbol id: parent type symbol ids}, from the caller's already# resolved heritage. Absent when the resolver is built standalone, in# which case the inherited tier simply never fires.self._heritage_parents: dict[str, set[str]] = heritage_parents or {}+ self._return_type_chain_languages = (+ PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES+ if return_type_chain_languages is None+ else return_type_chain_languages+ )self._ancestors: dict[str, tuple[str, ...]] = {}# Per-file symbol index: {file_path: {symbol_name: symbol_id}}self._file_symbols: dict[str, dict[str, str]] = {}@@ -216,6 +227,34 @@ class CallResolver:# Global symbol index: {name: [symbol_ids]} — for Tier 3self._global_symbols: dict[str, list[str]] = defaultdict(list)+ self._symbols_by_id = {+ symbol.id: symbol for parsed in parsed_files.values() for symbol in parsed.symbols+ }+ self._symbol_paths_by_id = {+ symbol.id: path+ for path, parsed in parsed_files.items()+ for symbol in parsed.symbols+ }+ self._overload_return_types: dict[tuple[str, str | None, str, int | None], set[str]] = (+ defaultdict(set)+ )+ for path, parsed in parsed_files.items():+ for symbol in parsed.symbols:+ raw_return = declared_return_type(symbol.signature or "")+ normalized = (+ normalize_return_type(raw_return, symbol.language) if raw_return else None+ )+ if normalized is not None:+ key = (+ path,+ symbol.parent_name,+ symbol.name,+ signature_parameter_count(symbol.signature or ""),+ )+ self._overload_return_types[key].add(normalized)+ self._known_type_names = frozenset(+ symbol.name for symbol in self._symbols_by_id.values() if symbol.kind in _TYPE_KINDS+ )# Symbols in the index above that are data members, not callables# (bug 90). Held as an id set rather than a full id→kind map because@@ -342,9 +381,7 @@ class CallResolver:# 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- ):+ if any(b.local_name == "*" and b.exported_name for b in imp.bindings):continueresolved = imp.resolved_fileif resolved != path:@@ -800,13 +837,7 @@ class CallResolver:for call in calls:if not call.caller_symbol_id:# Module-level call — assign to synthetic __module__ symbol- call = CallSite(- target_name=call.target_name,- receiver_name=call.receiver_name,- caller_symbol_id=f"{file_path}::__module__",- line=call.line,- argument_count=call.argument_count,- )+ call = replace(call, caller_symbol_id=f"{file_path}::__module__")resolved = self._resolve_one(file_path, call)if resolved:@@ -819,6 +850,15 @@ class CallResolver:caller_id = call.caller_symbol_idassert caller_id is not None+ language = self._language_of(file_path) or ""+ receiver_call = call.receiver_call+ if receiver_call is not None and language in self._return_type_chain_languages:+ handled, resolved = self._resolve_return_typed_chain(+ file_path, call, caller_id, language+ )+ if handled:+ return resolved+# --- Method call with receiver: receiver.method() ---if call.receiver_name:return self._resolve_member_call(file_path, call, caller_id)@@ -826,6 +866,92 @@ class CallResolver:# --- Free function call: function() ---return self._resolve_free_call(file_path, call, caller_id)+ def _resolve_return_typed_chain(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ language: str,+ ) -> tuple[bool, ResolvedCall | None]:+ """Resolve or reject a chained outer call using the inner return type.++ ``handled`` distinguishes a proven refusal from missing evidence. A+ known repository type that does not declare the outer method disproves+ the legacy bare-name fallback; an absent/external type leaves legacy+ behavior untouched.+ """++ inner = call.receiver_call+ assert inner is not None+ inner_call = CallSite(+ target_name=inner.target_name,+ receiver_name=inner.receiver_name,+ caller_symbol_id=caller_id,+ line=call.line,+ argument_count=inner.argument_count,+ )+ resolved_inner = self._resolve_one(file_path, inner_call)+ if resolved_inner is None:+ return False, None++ symbol = self._symbols_by_id.get(resolved_inner.callee_id)+ if symbol is None:+ return False, None+ if symbol.kind in _TYPE_KINDS:+ type_name = symbol.name+ else:+ raw_return = declared_return_type(symbol.signature or "")+ type_name = normalize_return_type(raw_return, language) if raw_return else None+ symbol_path = self._symbol_paths_by_id.get(resolved_inner.callee_id)+ if symbol_path is None:+ return False, None+ overload_key = (+ symbol_path,+ symbol.parent_name,+ symbol.name,+ inner.argument_count,+ )+ if len(self._overload_return_types.get(overload_key, ())) > 1:+ return False, None+ if type_name is None:+ return False, None++ found = self._typed_receiver_target(file_path, call, caller_id, type_name)+ if language == "java":+ # A simple type name is not repository-unique. Java package and+ # import binding settle its identity; the global tier does not.+ if found is None or found[1] == "global":+ return False, None+ elif language == "cpp":+ # P17 admits only the measured Seastar debt family. Broader C+++ # return-name matching remains probe evidence, not production+ # behaviour.+ if type_name != "future" or call.target_name != "get":+ return False, None+ if found is None:+ return (type_name in self._known_type_names), None+ elif language in ("csharp", "typescript"):+ # These lanes require a file or import/re-export identity. A+ # repository-global simple type name is not a language binding.+ if found is None or found[1] == "global":+ return False, None+ elif found is None:+ return (type_name in self._known_type_names), None++ assert found is not None+ sym_id, tier = found+ return True, self._return_typed_call(caller_id, sym_id, tier, call.line)++ def _return_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:+ """Stamp an edge whose receiver is the inner callee's return type."""+ if tier == "same_file":+ return ResolvedCall(caller_id, sym_id, 0.93, line, "return_type_same_file")+ if tier == "same_package":+ return ResolvedCall(caller_id, sym_id, 0.90, line, "return_type_same_package")+ if tier == "import":+ return ResolvedCall(caller_id, sym_id, 0.88, line, "return_type_import")+ return ResolvedCall(caller_id, sym_id, 0.75, line, "return_type_global")+def _member_shaped_sites(self, file_path: str) -> set[tuple[int, str]]:"""``(line, target)`` pairs at which this file also records a receiver.@@ -989,9 +1115,7 @@ class CallResolver:):sym_id = self._inherited_method(caller_id, target_name)if sym_id is not None:- return ResolvedCall(- caller_id, sym_id, 0.90, call.line, "enclosing_inherited"- )+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "enclosing_inherited")return None@@ -1270,9 +1394,7 @@ class CallResolver:exported = (binding.exported_name if binding else None) or type_namedeclaring = self._barrel_origins.get(bound, {}).get(exported)if declaring is not None and declaring != bound:- sym_id = self._file_methods.get(declaring, {}).get(- (exported, call.target_name)- )+ sym_id = self._file_methods.get(declaring, {}).get((exported, call.target_name))return None if sym_id is None else (sym_id, "import")# Bound to something outside the repo and there is no edge to find,@@ -1337,9 +1459,7 @@ class CallResolver:# Third scope: a module-level def a framework decorator turned into an# instance. Neither of the two above can see it — it is not in the body# and not a field.- from_framework = (- type_name is None and unbound and language in FRAMEWORK_DECORATOR_LANGUAGES- )+ from_framework = type_name is None and unbound and language in FRAMEWORK_DECORATOR_LANGUAGESif from_framework:# The type lookup is a dict hit and the shadowing scan reads the# whole file, so the cheap half decides first: only a receiver this@@ -1362,9 +1482,7 @@ class CallResolver:return self._field_typed_call(caller_id, sym_id, tier, call.line)return self._body_typed_call(caller_id, sym_id, tier, call.line)- def _body_typed_call(- self, caller_id: str, sym_id: str, tier: str, line: int- ) -> ResolvedCall:+ def _body_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:"""Stamp an edge whose receiver was typed from the calling body."""if tier == "same_file":return ResolvedCall(caller_id, sym_id, 0.93, line, "receiver_typed_same_file")@@ -1374,9 +1492,7 @@ class CallResolver:return ResolvedCall(caller_id, sym_id, 0.88, line, "receiver_typed_import")return ResolvedCall(caller_id, sym_id, 0.75, line, "receiver_typed_global")- def _field_typed_call(- self, caller_id: str, sym_id: str, tier: str, line: int- ) -> ResolvedCall:+ def _field_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:"""Stamp an edge whose receiver was typed from the enclosing class."""if tier == "same_file":return ResolvedCall(caller_id, sym_id, 0.93, line, "receiver_field_same_file")@@ -1464,9 +1580,7 @@ class CallResolver:parsed = self._parsed_files.get(file_path)symbols = parsed.symbols if parsed else ()- class_spans = {- s.id: (s.start_line, s.end_line) for s in symbols if s.kind in _TYPE_KINDS- }+ class_spans = {s.id: (s.start_line, s.end_line) for s in symbols if s.kind in _TYPE_KINDS}by_class = types_by_class(self._declarations_for(file_path, language),class_spans,@@ -1477,9 +1591,7 @@ class CallResolver:self._field_types[file_path] = by_classreturn by_class- def _bound_names_in(- self, file_path: str, caller_id: str, language: str- ) -> frozenset[str]:+ def _bound_names_in(self, file_path: str, caller_id: str, language: str) -> frozenset[str]:"""Every name the calling body binds, however it was bound."""key = (file_path, caller_id)names = self._bound_names.get(key)@@ -1538,9 +1650,7 @@ class CallResolver:self._framework_types[file_path] = typesreturn types- def _framework_type_of(- self, file_path: str, receiver_name: str, language: str- ) -> str | None:+ def _framework_type_of(self, file_path: str, receiver_name: str, language: str) -> str | None:"""The framework type of *receiver_name*, where this file can see it.Declared here, or imported here by name. A decorated def in a file the@@ -1598,9 +1708,7 @@ class CallResolver:text = ""if parsed is not None:try:- text = Path(parsed.file_info.abs_path).read_text(- encoding="utf-8", errors="ignore"- )+ text = Path(parsed.file_info.abs_path).read_text(encoding="utf-8", errors="ignore")except OSError:text = ""diff --git a/packages/core/src/repowise/core/ingestion/extractors/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.pyindex 27593ba22..858239c10 100644--- a/packages/core/src/repowise/core/ingestion/extractors/signatures.py+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py@@ -26,6 +26,10 @@ def build_signature(node_type: str, name: str, params_text: str, def_node: Node,return ""if node_type == "function_definition":+ # C/C++ share this node name with Python but expose the declared type+ # through ``type`` rather than ``return_type``.+ if def_node.child_by_field_name("type") is not None:+ return f"{name}{params_text}{_ret(('type',))}"# Detect async via child "async" keyword (tree-sitter-python >= 0.23)prefix = "async " if any(c.type == "async" for c in def_node.children) else ""return f"{prefix}def {name}{params_text}{_ret(('return_type',))}"diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 2ad76d619..5cfa421b7 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -230,6 +230,19 @@ class Import:is_reexport: bool = False # True for `pub use` (Rust) or re-export patterns+@dataclass+class CallReceiver:+ """A call expression used as the receiver of another call.++ Keeping this AST-derived fact separate from ``receiver_name`` prevents a+ chained call from being mistaken for an unqualified/free call.+ """++ target_name: str+ receiver_name: str | None+ argument_count: int | None++@dataclassclass CallSite:"""A function or method call extracted from a source file.@@ -242,6 +255,7 @@ class CallSite:caller_symbol_id: str | None # enclosing symbol ID (e.g. "src/app.py::main")line: int # 1-indexed line number of the callargument_count: int | None # number of arguments (None if unknown)+ receiver_call: CallReceiver | None = None # set only for a captured chained callHeritageKind = Literal["extends", "implements", "trait_impl", "mixin"]@@ -391,6 +405,11 @@ ResolutionOrigin = Literal["receiver_framework_same_package", # 0.90"receiver_framework_import", # 0.88"receiver_framework_global", # 0.75+ # Chained receiver typed from the inner callee's declared return type.+ "return_type_same_file", # 0.93+ "return_type_same_package", # 0.90 (JVM)+ "return_type_import", # 0.88+ "return_type_global", # 0.75# 0.90 — the caller's own class does not declare the method but exactly one# of its ancestors does. Below the two same-class origins because the walk# compares no signature and reads no visibility, so it can reach a methoddiff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex a645920d9..e274d31d9 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -59,6 +59,7 @@ from .extractors.visibility import (from .language_configs import LANGUAGE_CONFIGS, LanguageConfigfrom .languages.registry import REGISTRY as _LANG_REGISTRYfrom .models import (+ CallReceiver,CallSite,FileInfo,Import,@@ -114,15 +115,62 @@ _TS_JS_LANGUAGES = ("typescript", "javascript", "svelte", "vue")_REFERENCE_LANGUAGES = ("cpp", "c", "go", "rust", "kotlin")+def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:+ """Describe an inner call captured as another call's receiver.++ The queries identify the complete inner AST node. This helper reads only+ named tree-sitter fields, so nested arguments and formatting cannot change+ which call is carried into resolution.+ """++ arguments = node.child_by_field_name("arguments")+ argument_count = _count_arguments(arguments) if arguments is not None else None++ target = node.child_by_field_name("name")+ receiver = node.child_by_field_name("object")+ if target is None:+ function = node.child_by_field_name("function")+ if function is None:+ return None+ if function.type in ("identifier", "property_identifier", "field_identifier"):+ target = function+ receiver = None+ elif function.type == "generic_name":+ target = function.child_by_field_name("name") or next(+ (child for child in function.named_children if child.type == "identifier"), None+ )+ receiver = None+ else:+ target = (+ function.child_by_field_name("name")+ or function.child_by_field_name("property")+ or function.child_by_field_name("field")+ )+ receiver = (+ function.child_by_field_name("expression")+ or function.child_by_field_name("object")+ or function.child_by_field_name("argument")+ )++ if target is None:+ return None+ target_name = _node_text(target, src).strip()+ if not target_name:+ return None++ receiver_name = None+ if receiver is not None and receiver.type in ("identifier", "this"):+ receiver_name = _node_text(receiver, src).strip() or None+ return CallReceiver(target_name, receiver_name, argument_count)++# C/C++ node types that spell a type. Each one covers both the definition and# the forward declaration of that type; only the ``body`` field tells them# apart. See ``_is_bodiless_cpp_type``.# ``union_specifier`` is absent because neither grammar's query captures one# as a symbol today. If a union capture is ever added, add it here too, or a# bodiless ``union U;`` goes back to reading as a definition.-_CPP_TYPE_SPECIFIER_NODES = frozenset(- {"class_specifier", "struct_specifier", "enum_specifier"}-)+_CPP_TYPE_SPECIFIER_NODES = frozenset({"class_specifier", "struct_specifier", "enum_specifier"})def _is_bodiless_cpp_type(language: str, node_type: str, def_node: Node) -> bool:@@ -1157,13 +1205,13 @@ class ASTParser:)calls: list[CallSite] = []- seen: set[tuple[int, str, str | None]] = set()for capture_dict in matches:site_nodes = capture_dict.get("call.site", [])target_nodes = capture_dict.get("call.target", [])arg_nodes = capture_dict.get("call.arguments", [])receiver_nodes = capture_dict.get("call.receiver", [])+ receiver_call_nodes = capture_dict.get("call.receiver_call", [])if not site_nodes or not target_nodes:continue@@ -1180,11 +1228,11 @@ class ASTParser:receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else Noneif receiver_name and file_info.language == "php":receiver_name = _normalize_php_receiver(receiver_name)-- dedup_key = (line, target_name, receiver_name)- if dedup_key in seen:- continue- seen.add(dedup_key)+ receiver_call = (+ _call_receiver_from_node(receiver_call_nodes[0], src)+ if receiver_call_nodes+ else None+ )arg_count: int | None = Noneif arg_nodes:@@ -1200,10 +1248,20 @@ class ASTParser:caller_symbol_id=caller_id,line=line,argument_count=arg_count,+ receiver_call=receiver_call,))- return calls+ deduplicated: dict[tuple[int, str, str | None], CallSite] = {}+ for call in calls:+ key = (call.line, call.target_name, call.receiver_name)+ existing = deduplicated.get(key)+ if existing is None or (+ existing.receiver_call is None+ and call.receiver_call is not None+ ):+ deduplicated[key] = call+ return list(deduplicated.values())def _extract_references(self,diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex a7cf0fcf1..8457c454c 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -204,7 +204,7 @@; Chained call: obj.method1().method2(args)(call_expressionfunction: (field_expression- argument: (call_expression)+ argument: (call_expression) @call.receiver_callfield: (field_identifier) @call.target)arguments: (argument_list) @call.argumentsdiff --git a/packages/core/src/repowise/core/ingestion/queries/csharp.scm b/packages/core/src/repowise/core/ingestion/queries/csharp.scmindex 694f7dfc2..36901da88 100644--- a/packages/core/src/repowise/core/ingestion/queries/csharp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/csharp.scm@@ -205,6 +205,19 @@arguments: (argument_list) @call.arguments) @call.site+; Chained call: factory().Method(args). Carry the inner invocation as an AST+; node so resolution can use its declared return type without scanning text.+(invocation_expression+ function: (member_access_expression+ expression: (invocation_expression) @call.receiver_call+ name: [+ (identifier) @call.target+ (generic_name (identifier) @call.target)+ ]+ )+ arguments: (argument_list) @call.arguments+) @call.site+; Fluent construction: new Builder().Method(args).; The receiver is captured from the constructed type rather than from a; variable, because here the type is written at the call site. That keeps thediff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scmindex 0f1191b68..ff4674fa9 100644--- a/packages/core/src/repowise/core/ingestion/queries/java.scm+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm@@ -150,7 +150,7 @@; Chained method call: obj.method1().method2(args)(method_invocation- object: (method_invocation)+ object: (method_invocation) @call.receiver_callname: (identifier) @call.targetarguments: (argument_list) @call.arguments) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex 08c1d51c0..9eccd0d15 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -240,7 +240,7 @@; Chained call: obj.method1().method2(args)(call_expressionfunction: (member_expression- object: (call_expression)+ object: (call_expression) @call.receiver_callproperty: (property_identifier) @call.target)arguments: (arguments) @call.argumentsdiff --git a/packages/core/src/repowise/core/ingestion/return_types.py b/packages/core/src/repowise/core/ingestion/return_types.pynew file mode 100644index 000000000..181b982ed--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/return_types.py@@ -0,0 +1,70 @@+"""Normalization for declared return types used by chained-call resolution."""++from __future__ import annotations++import re++from .type_names import bare_type_name++_NULLISH_UNION = re.compile(r"\s*\|\s*(?:null|undefined)\b")+_CPP_PREFIX = re.compile(r"^(?:(?:const|volatile|typename|class|struct)\s+)+")+_CPP_SUFFIX = re.compile(r"\s*(?:\*|&|&&)\s*$")+++def declared_return_type(signature: str) -> str | None:+ """Return the declared portion of a stored symbol signature, if present."""++ _, separator, raw = signature.partition(" -> ")+ value = raw.strip() if separator else ""+ return value or None+++def signature_parameter_count(signature: str) -> int | None:+ """Count top-level parameters in a stored callable signature."""++ start = signature.find("(")+ if start < 0:+ return None+ depth = 0+ commas = 0+ content = False+ pairs = {"(": ")", "[": "]", "{": "}", "<": ">"}+ closers: list[str] = []+ for char in signature[start + 1 :]:+ if char == ")" and not closers:+ return commas + 1 if content else 0+ if char in pairs:+ closers.append(pairs[char])+ depth += 1+ elif closers and char == closers[-1]:+ closers.pop()+ depth -= 1+ elif char == "," and depth == 0:+ commas += 1+ elif not char.isspace() and depth == 0:+ content = True+ return None+++def normalize_return_type(raw: str, language: str) -> str | None:+ """Reduce a named return type to the repository's class-name key.++ Generic arguments are intentionally not unwrapped: ``future<T>.get()`` is+ a method on ``future``, not on ``T``. Language-specific punctuation is+ removed here, at the boundary where signatures enter resolution.+ """++ value = raw.strip()+ if language in ("typescript", "javascript", "svelte", "vue"):+ value = _NULLISH_UNION.sub("", value).strip()+ if language == "csharp":+ value = value.removeprefix("global::").rstrip("?").strip()+ if language == "java":+ value = value.rstrip("?").strip()+ if language == "cpp":+ value = _CPP_PREFIX.sub("", value)+ while _CPP_SUFFIX.search(value):+ value = _CPP_SUFFIX.sub("", value)++ name = bare_type_name(value).strip()+ return name if name.isidentifier() else Nonediff --git a/packages/types/src/graph.ts b/packages/types/src/graph.tsindex 643a5ae5c..dae64b00e 100644--- a/packages/types/src/graph.ts+++ b/packages/types/src/graph.ts@@ -271,6 +271,10 @@ export type ResolutionOrigin =| "receiver_framework_same_package"| "receiver_framework_import"| "receiver_framework_global"+ | "return_type_same_file"+ | "return_type_same_package"+ | "return_type_import"+ | "return_type_global"| "self_inherited"| "enclosing_inherited";diff --git a/packages/ui/__tests__/graph/edge-provenance.test.ts b/packages/ui/__tests__/graph/edge-provenance.test.tsindex 08950747d..551cbaf8c 100644--- a/packages/ui/__tests__/graph/edge-provenance.test.ts+++ b/packages/ui/__tests__/graph/edge-provenance.test.ts@@ -50,6 +50,10 @@ const ALL_ORIGINS: ResolutionOrigin[] = ["receiver_framework_same_package","receiver_framework_import","receiver_framework_global",+ "return_type_same_file",+ "return_type_same_package",+ "return_type_import",+ "return_type_global","self_inherited","enclosing_inherited",];@@ -107,6 +111,7 @@ describe("isNameMatch", () => {"receiver_framework_global","receiver_global","receiver_typed_global",+ "return_type_global",].sort(),);});diff --git a/packages/ui/src/graph/edge-provenance.ts b/packages/ui/src/graph/edge-provenance.tsindex 74f000d41..9d008f084 100644--- a/packages/ui/src/graph/edge-provenance.ts+++ b/packages/ui/src/graph/edge-provenance.ts@@ -66,6 +66,11 @@ const ORIGINS = {because: "a framework decorator retyped the receiver, and that class is in this file",tier: "direct",},+ return_type_same_file: {+ label: "Return type, same file",+ because: "the inner call's declared return type is a class in this file",+ tier: "direct",+ },// --- scoped: an import, a package, a module, a supertype ---------------same_package: {@@ -143,6 +148,16 @@ const ORIGINS = {because: "a framework decorator retyped the receiver, and that class was found in an imported file",tier: "scoped",},+ return_type_same_package: {+ label: "Return type, same package",+ because: "the inner call's declared return type is a class in the same package",+ tier: "scoped",+ },+ return_type_import: {+ label: "Return type, imported",+ because: "the inner call's declared return type was found in an imported file",+ tier: "scoped",+ },self_inherited: {label: "Inherited",because: "the caller's class does not declare it but one ancestor does",@@ -175,6 +190,11 @@ const ORIGINS = {because: "the framework type and method pair exists somewhere in the repo",tier: "name_match",},+ return_type_global: {+ label: "Name match",+ because: "the returned type and method pair exists somewhere in the repo",+ tier: "name_match",+ },global_unique: {label: "Name match",because: "the name is unique across the repo, so nothing else could match",diff --git a/tests/unit/ingestion/parser/test_chained_call_receivers.py b/tests/unit/ingestion/parser/test_chained_call_receivers.pynew file mode 100644index 000000000..04b19f442--- /dev/null+++ b/tests/unit/ingestion/parser/test_chained_call_receivers.py@@ -0,0 +1,64 @@+from __future__ import annotations++import pytest++from repowise.core.ingestion.parser import ASTParser+from tests.unit.ingestion.parser._helpers import _make_file_info+++ ("path", "language", "source", "outer", "inner", "receiver"),+ [+ (+ "Example.java",+ "java",+ b"class Example { void use(Service service) { service.factory(1).run(); } }",+ "run",+ "factory",+ "service",+ ),+ (+ "example.cpp",+ "cpp",+ b"void use(Service service) { service.factory(1).run(); }",+ "run",+ "factory",+ "service",+ ),+ (+ "Example.cs",+ "csharp",+ b"class Example { void Use(Service service) { service.Factory(1).Run(); } }",+ "Run",+ "Factory",+ "service",+ ),+ (+ "example.ts",+ "typescript",+ b"function use(service: Service) { service.factory(1).run(); }",+ "run",+ "factory",+ "service",+ ),+ ],+)+def test_chained_call_carries_structural_inner_call(+ parser: ASTParser,+ path: str,+ language: str,+ source: bytes,+ outer: str,+ inner: str,+ receiver: str,+) -> None:+ parsed = parser.parse_file(_make_file_info(path, language), source)+ call = next(+ c for c in parsed.calls if c.target_name == outer and getattr(c, "receiver_call", None)+ )++ assert call.receiver_name is None+ assert call.receiver_call is not None+ assert call.receiver_call.target_name == inner+ assert call.receiver_call.receiver_name == receiver+ assert call.receiver_call.argument_count == 1diff --git a/tests/unit/ingestion/parser/test_method_signatures.py b/tests/unit/ingestion/parser/test_method_signatures.pyindex 2f39f9f96..6ed5a09eb 100644--- a/tests/unit/ingestion/parser/test_method_signatures.py+++ b/tests/unit/ingestion/parser/test_method_signatures.py@@ -23,6 +23,13 @@ from tests.unit.ingestion.parser._helpers import _make_file_info"Get","Get(K key) -> V",),+ (+ "example.cpp",+ "cpp",+ b"Widget make(int key) { return Widget(); }",+ "make",+ "make(int key) -> Widget",+ ),("example.go","go",diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.pynew file mode 100644index 000000000..9d2909d1c--- /dev/null+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py@@ -0,0 +1,239 @@+from __future__ import annotations++from datetime import datetime+from pathlib import Path++import pytest++from repowise.core.ingestion.call_resolver import (+ PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES,+ CallResolver,+)+from repowise.core.ingestion.models import FileInfo, ParsedFile+from repowise.core.ingestion.parser import parse_file+++def _parse(tmp_path: Path, path: str, language: str, source: str) -> dict[str, ParsedFile]:+ absolute = tmp_path / path+ absolute.write_text(source, encoding="utf-8")+ info = FileInfo(+ path=path,+ abs_path=str(absolute),+ language=language, # type: ignore[arg-type]+ size_bytes=len(source),+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ return {path: parse_file(info, source.encode())}+++ ("path", "language", "source", "outer", "expected_type"),+ [+ (+ "Example.java",+ "java",+ "class Product { void run() {} }\nclass Wrong { void run() {} }\n"+ "class Use {\n Product make() { return new Product(); }\n void go() { make().run(); }\n}",+ "run",+ "Product",+ ),+ (+ "example.cpp",+ "cpp",+ "template<typename T> struct future { T get() {} };\n"+ "struct Wrong { int get() {} };\n"+ "future<int> make() { return {}; }\nvoid use() { make().get(); }",+ "get",+ "future",+ ),+ (+ "Example.cs",+ "csharp",+ "class Product { public void Run() {} }\nclass Wrong { public void Run() {} }\n"+ "class Use {\n Product Make() { return new Product(); }\n void Go() { Make().Run(); }\n}",+ "Run",+ "Product",+ ),+ (+ "example.ts",+ "typescript",+ "class Product { run() {} }\nclass Wrong { run() {} }\n"+ "function make(): Product { return new Product(); }\nfunction use() { make().run(); }",+ "run",+ "Product",+ ),+ ],+)+def test_return_type_chain_retargets_to_declared_type(+ tmp_path: Path,+ path: str,+ language: str,+ source: str,+ outer: str,+ expected_type: str,+) -> None:+ parsed = _parse(tmp_path, path, language, source)+ call = next(+ c+ for c in parsed[path].calls+ if c.target_name == outer and getattr(c, "receiver_call", None)+ )++ control = CallResolver(+ parsed, {}, repo_path=str(tmp_path), return_type_chain_languages=frozenset()+ )+ treatment = CallResolver(+ parsed, {}, repo_path=str(tmp_path), return_type_chain_languages=frozenset({language})+ )+ before = control.resolve_file(path, [call])+ after = treatment.resolve_file(path, [call])++ assert not any(edge.origin.startswith("return_type_") for edge in before)+ assert len(after) == 1+ assert after[0].callee_id.endswith(f"::{expected_type}::{outer}")+ assert after[0].origin.startswith("return_type_")+++def test_java_unknown_member_preserves_legacy_fallback(tmp_path: Path) -> None:+ source = (+ "class Product {} class Wrong { void run() {} } "+ "class Use { Product make() { return new Product(); } void go() { make().run(); } }"+ )+ parsed = _parse(tmp_path, "Example.java", "java", source)+ call = next(+ c+ for c in parsed["Example.java"].calls+ if c.target_name == "run" and getattr(c, "receiver_call", None)+ )++ before = CallResolver(parsed, {}, return_type_chain_languages=frozenset()).resolve_file(+ "Example.java", [call]+ )+ after = CallResolver(parsed, {}, return_type_chain_languages=frozenset({"java"})).resolve_file(+ "Example.java", [call]+ )++ assert len(before) == 1+ assert after == before+++def test_java_ambiguous_overload_return_preserves_legacy_fallback(tmp_path: Path) -> None:+ source = (+ "class First { void run() {} }\nclass Second { void run() {} }\n"+ "class Factory {\n First make(int value) { return new First(); }\n"+ " Second make(String value) { return new Second(); }\n}\n"+ "class Use { void go() { new Factory().make(1).run(); } }\n"+ )+ parsed = _parse(tmp_path, "Example.java", "java", source)+ call = next(+ c+ for c in parsed["Example.java"].calls+ if c.target_name == "run" and getattr(c, "receiver_call", None) and c.line == 7+ )++ before = CallResolver(parsed, {}, return_type_chain_languages=frozenset()).resolve_file(+ "Example.java", [call]+ )+ after = CallResolver(parsed, {}, return_type_chain_languages=frozenset({"java"})).resolve_file(+ "Example.java", [call]+ )++ assert after == before+++def test_cpp_future_get_can_refuse_a_bare_name_fallback(tmp_path: Path) -> None:+ source = (+ "template<typename T> struct future {}; struct Wrong { int get() {} }; "+ "future<int> make() { return {}; } void use() { make().get(); }"+ )+ parsed = _parse(tmp_path, "example.cpp", "cpp", source)+ call = next(+ c+ for c in parsed["example.cpp"].calls+ if c.target_name == "get" and getattr(c, "receiver_call", None)+ )++ before = CallResolver(parsed, {}, return_type_chain_languages=frozenset()).resolve_file(+ "example.cpp", [call]+ )+ after = CallResolver(parsed, {}, return_type_chain_languages=frozenset({"cpp"})).resolve_file(+ "example.cpp", [call]+ )++ assert len(before) == 1+ assert after == []+++ ("language", "product_source", "use_source", "outer"),+ [+ (+ "csharp",+ "class Product { public void Run() {} }",+ "class Use { Product Make() { return new Product(); } void Go() { Make().Run(); } }",+ "Run",+ ),+ (+ "typescript",+ "export class Product { run() {} }",+ "function make(): Product { return null as any; } function use() { make().run(); }",+ "run",+ ),+ ],+)+def test_unbound_global_return_type_preserves_legacy_fallback(+ tmp_path: Path,+ language: str,+ product_source: str,+ use_source: str,+ outer: str,+) -> None:+ extension = "cs" if language == "csharp" else "ts"+ parsed = {}+ parsed.update(_parse(tmp_path, f"Product.{extension}", language, product_source))+ parsed.update(_parse(tmp_path, f"Use.{extension}", language, use_source))+ use_path = f"Use.{extension}"+ call = next(+ c+ for c in parsed[use_path].calls+ if c.target_name == outer and getattr(c, "receiver_call", None)+ )++ before = CallResolver(parsed, {}, return_type_chain_languages=frozenset()).resolve_file(+ use_path, [call]+ )+ after = CallResolver(+ parsed, {}, return_type_chain_languages=frozenset({language})+ ).resolve_file(use_path, [call])++ assert after == before+++def test_only_audited_cpp_lane_is_enabled_by_default() -> None:+ assert frozenset({"cpp"}) == PRODUCTION_RETURN_TYPE_CHAIN_LANGUAGES+++def test_module_level_chain_keeps_structural_receiver(tmp_path: Path) -> None:+ source = (+ "class Product { run() {} }\n"+ "function make(): Product { return new Product(); }\n"+ "make().run();\n"+ )+ parsed = _parse(tmp_path, "example.ts", "typescript", source)+ call = next(+ c+ for c in parsed["example.ts"].calls+ if c.target_name == "run" and getattr(c, "receiver_call", None)+ )++ result = CallResolver(+ parsed, {}, return_type_chain_languages=frozenset({"typescript"})+ ).resolve_file("example.ts", [call])++ assert result[0].caller_id == "example.ts::__module__"+ assert result[0].callee_id.endswith("::Product::run")diff --git a/tests/unit/ingestion/test_return_types.py b/tests/unit/ingestion/test_return_types.pynew file mode 100644index 000000000..655ecb035--- /dev/null+++ b/tests/unit/ingestion/test_return_types.py@@ -0,0 +1,42 @@+from __future__ import annotations++import pytest++from repowise.core.ingestion.return_types import (+ declared_return_type,+ normalize_return_type,+ signature_parameter_count,+)+++def test_declared_return_type_reads_stored_signature() -> None:+ assert declared_return_type("factory() -> java.util.List<Item>") == "java.util.List<Item>"+ assert declared_return_type("factory()") is None+++ ("signature", "expected"),+ [+ ("run() -> void", 0),+ ("make(Map<String, Integer> values, int count) -> Product", 2),+ ("broken", None),+ ],+)+def test_signature_parameter_count(signature: str, expected: int | None) -> None:+ assert signature_parameter_count(signature) == expected+++ ("raw", "language", "expected"),+ [+ ("Result", "java", "Result"),+ ("java.util.Optional<Result>", "java", "Optional"),+ ("const seastar::future<Result>&", "cpp", "future"),+ ("global::System.Threading.Tasks.Task<Result>?", "csharp", "Task"),+ ("Promise<Result> | null", "typescript", "Promise"),+ ],+)+def test_normalize_return_type_keeps_the_declared_wrapper(+ raw: str, language: str, expected: str+) -> None:+ assert normalize_return_type(raw, language) == expected