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(dead-code): detect JSX prop-guard dead code (#1554) (#1570)
Rishabh Mishra0cbe36f70f0d
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex a41a05498..8a947913d 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -678,6 +678,7 @@ class DeadCodeAnalyzer:# along so the evidence line can say why.self._unindexed_source_files = list(unindexed_source_files or [])self._repo_root = repo_root+ self._source_map = source_mapself._unindexed_tokens: frozenset[str] | None = None# Kept for the absence check below, which is the one pass that needs# the raw text of *every* indexed file rather than of a suffix-filtered@@ -733,6 +734,11 @@ class DeadCodeAnalyzer:# because the whitelist arrives per ``analyze()`` call and the map does# not.self._package_files: PackageFileMap | None = None+ # Cache for JSX prop-guard extraction: maps pred_file → list of+ # (parent_fn, child_component, guard_prop) triples. Populated lazily+ # by _get_unsatisfied_prop_guard so each TSX/JSX file is read from+ # disk and parsed by tree-sitter at most once per analysis run.+ self._guard_cache: dict[str, list[tuple[str, str, str]]] = {}def _reachability_rescues(self, whitelist: AbstractSet[str]) -> ReachabilityRescues:"""Assemble the rescue state the shared predicate reads."""@@ -1329,6 +1335,8 @@ class DeadCodeAnalyzer:# alias; importers carry the alias in ``imported_names``.export_alias = self._ts_export_aliases.get(str(node), {}).get(sym_name)+ unsatisfied_guard: tuple[str, str] | None = None+has_importers = Falsefor pred in self.graph.predecessors(node):edge_data = self.graph[pred][node]@@ -1342,13 +1350,17 @@ class DeadCodeAnalyzer:breakif has_importers:- continue+ node_lang = node_data.get("language", "")+ if node_lang in ("typescript", "javascript"):+ unsatisfied_guard = self._get_unsatisfied_prop_guard(sym_id, sym_name)+ if unsatisfied_guard is None:+ continue# Namespace-import rescue: see ``file_imported_as_namespace``# computation above. Any public symbol in a file pulled by# module name could be the dispatch target for# ``<modname>.<attr>(...)``.- if file_imported_as_namespace:+ if file_imported_as_namespace and unsatisfied_guard is None:continue# Symbol-level usage signal: any incoming ``calls`` /@@ -1356,102 +1368,65 @@ class DeadCodeAnalyzer:# ``implements`` / ``type_use`` edge means somewhere in# the codebase actually uses this symbol — even if the# file-level ``imported_names`` machinery missed it- # (intra-file C++ helpers, ``Foo::method`` qualified- # definitions linked by call resolution but never named- # in a header, Razor/XAML code-behind dispatches, and- # abstract base classes / interfaces that are only ever- # extended or implemented, never called directly — Java- # padding bases like ``BoundedLocalCache.BLCHeader``,- # Kotlin sealed parents, Scala typeclass traits).- if self.graph.has_node(sym_id) and any(- self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES- for pred in self.graph.predecessors(sym_id)+ if (+ unsatisfied_guard is None+ and self.graph.has_node(sym_id)+ and any(+ self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES+ for pred in self.graph.predecessors(sym_id)+ )):continue- # A container whose member is used is itself used, and no- # search for the container's own name can see it. A C# static- # holder class is only ever named at its declaration --- # ``Guard.Against.EmptyBasket(...)`` writes the method, never- # ``BasketGuards`` -- so the name really is absent and the name- # is the wrong thing to look for. Asked after the direct check- # so it can only rescue, never displace.- #- # Gated to C# because that is where the idiom lives. The- # argument generalises -- deleting any class whose method has a- # caller breaks that caller -- but ungating it removes findings- # in every language at once, which is its own measured change.if self._member_is_used(sym_id, sym.get("language")):continue- if is_deprecated:- confidence = 0.3- elif file_has_importers:- confidence = 1.0- else:- confidence = 0.7-- # Interfaces / protocols are reached almost exclusively- # through their implementors. Implementor detection is- # heuristic — its absence is "evidence missing", not- # "evidence of absence". Cap confidence below the- # safe-to-delete threshold when the file containing the- # interface has no incoming ``implements``-class edges,- # so the demo doesn't ship public-API interfaces as- # confident dead code. Generic across all languages- # (C#, Java, Kotlin, Scala, Swift protocols, TS).- if sym.get("kind") == "interface" and not self._file_has_implementors(node):- confidence = min(confidence, RISK_CAP_CONFIDENCE)-- # COM / IUnknown / IDispatch contract methods- # (``QueryInterface``, ``AddRef``, ``Release``, …) are- # dispatched through native vtables — no static caller- # edge will ever land in the graph. Clamp below the- # safe-to-delete threshold so we never ship them as- # confident dead code on Windows / COM-heavy C++ repos.- if is_contract_method(sym_name, sym.get("kind"), sym.get("language", "unknown")):- confidence = min(confidence, RISK_CAP_CONFIDENCE)-- # Runtime-load risk factors for the defining file (config /- # bootstrap / database / environment / script / asset): symbols in- # such files are often wired up reflectively, so cap below the- # deletion-ready threshold and tag the finding for review.risk_factors = path_risk_factors(str(node))- if risk_factors:- confidence = min(confidence, RISK_CAP_CONFIDENCE)-- # Unresolved dynamic-use clamp — the same package-level question- # the unreachable-files pass asks (see ``_make_unreachable_finding``).- # A public symbol in a package whose source uses runtime-dispatch- # machinery (``importlib``, entry points, reflection, ``getattr``- # keyed by a configured string) can be wired up without any static- # edge: a registry value, a callback, a plugin looked up by a name- # the graph never sees. ``file_dynamically_loaded`` above only- # rescues the *resolved* case — a ``dynamic_uses``/``framework``- # edge the extractors actually minted. This clamp covers the- # unresolved case, where the mechanism is present but the target- # is not pinned: it may lower confidence and must clear- # ``safe_to_delete``, and it must never raise either. The finding- # stays in the report as a review candidate (the cap lands exactly- # on the default ``min_confidence``), exactly like the sibling- # clamp on unreachable files.- if self._dynamic_import_dirs and str(Path(node).parent) in self._dynamic_import_dirs:- confidence = min(confidence, RISK_CAP_CONFIDENCE)-- safe = confidence >= SAFE_CONFIDENCE_THRESHOLD+ file_basename = Path(node).name++ if unsatisfied_guard:+ guard_prop, caller_name = unsatisfied_guard+ confidence = RISK_CAP_CONFIDENCE+ if risk_factors:+ confidence = min(confidence, RISK_CAP_CONFIDENCE)+ safe = False+ reason = f"Public symbol '{sym_name}' is rendered behind prop guard '{guard_prop}' which is never supplied"+ evidence = [f"Prop '{guard_prop}' is missing across all call sites of '{caller_name}'"]+ else:+ if is_deprecated:+ confidence = 0.3+ elif file_has_importers:+ confidence = 1.0+ else:+ confidence = 0.7++ if sym.get("kind") == "interface" and not self._file_has_implementors(node):+ confidence = min(confidence, RISK_CAP_CONFIDENCE)++ if is_contract_method(sym_name, sym.get("kind"), sym.get("language", "unknown")):+ confidence = min(confidence, RISK_CAP_CONFIDENCE)++ if risk_factors:+ confidence = min(confidence, RISK_CAP_CONFIDENCE)++ if self._dynamic_import_dirs and str(Path(node).parent) in self._dynamic_import_dirs:+ confidence = min(confidence, RISK_CAP_CONFIDENCE)++ safe = confidence >= SAFE_CONFIDENCE_THRESHOLD++ evidence = [f"No file imports symbol '{sym_name}' from {file_basename}"]+ risk_line = risk_evidence(risk_factors)+ if risk_line:+ evidence.append(risk_line)+ if self._dynamic_import_files and confidence <= RISK_CAP_CONFIDENCE:+ evidence.append(+ "Package uses dynamic imports or runtime-resolved edges, "+ "so the absence of a static reference does not establish disuse"+ )+ reason = f"Public symbol '{sym_name}' has no importers"git_meta = self.git_meta_map.get(str(node), {})- evidence = [f"No imports of '{sym_name}' found in graph"]- risk_line = risk_evidence(risk_factors)- if risk_line:- evidence.append(risk_line)- if self._dynamic_import_files and confidence <= RISK_CAP_CONFIDENCE:- evidence.append(- "Package uses dynamic imports or runtime-resolved edges, "- "so the absence of a static reference does not establish disuse"- )-findings.append(DeadCodeFindingData(kind=DeadCodeKind.UNUSED_EXPORT,@@ -1459,7 +1434,7 @@ class DeadCodeAnalyzer:symbol_name=sym_name,symbol_kind=sym.get("kind"),confidence=confidence,- reason=f"Public symbol '{sym_name}' has no importers",+ reason=reason,last_commit_at=git_meta.get("last_commit_at")if isinstance(git_meta.get("last_commit_at"), datetime)else None,@@ -1478,6 +1453,91 @@ class DeadCodeAnalyzer:return findings+ def _get_unsatisfied_prop_guard(+ self, sym_id: str, sym_name: str, visited: set[str] | None = None+ ) -> tuple[str, str] | None:+ """Check if a symbol is rendered behind a prop guard that is never supplied."""+ if not self.graph.has_node(sym_id):+ return None++ if visited is None:+ visited = set()+ if sym_id in visited:+ return None+ visited.add(sym_id)++ from .jsx_prop_guards import extract_guarded_jsx_renders++ predecessors = [+ pred for pred in self.graph.predecessors(sym_id)+ if self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES+ ]+ if not predecessors:+ return None++ for pred in predecessors:+ pred_file = pred.split("::")[0] if "::" in pred else pred+ if not pred_file.endswith((".tsx", ".jsx", ".ts", ".js")):+ continue++ if pred_file not in self._guard_cache:+ src = self._read_file_text(pred_file)+ self._guard_cache[pred_file] = (+ extract_guarded_jsx_renders(pred_file, src) if src else []+ )+ pred_parent = pred.split("::")[-1] if "::" in pred else None+ guarded = self._guard_cache[pred_file]+ found_guard = None+ for parent_fn, child_comp, prop_name in guarded:+ if child_comp == sym_name and (+ pred_parent is None or parent_fn == pred_parent or parent_fn == "Anonymous"+ ):+ found_guard = (prop_name, parent_fn if parent_fn != "Anonymous" else (pred_parent or ""))+ break++ if found_guard:+ prop_name, parent_name = found_guard+ incoming = [+ caller for caller in self.graph.predecessors(pred)+ if self.graph[caller][pred].get("edge_type") in REACHABILITY_USE_EDGE_TYPES+ ]+ if incoming:+ all_missing = True+ for caller in incoming:+ edge = self.graph[caller][pred]+ supplied = edge.get("supplied_props")+ if supplied is None or prop_name in supplied:+ all_missing = False+ break+ if all_missing:+ return (prop_name, parent_name)++ pred_name = pred.split("::")[-1]+ parent_guard = self._get_unsatisfied_prop_guard(pred, pred_name, visited)+ if parent_guard is not None:+ return parent_guard++ return None++ def _read_file_text(self, file_path: str) -> str | None:+ """Safely read the content of a file, using source_map if available."""+ try:+ if getattr(self, "_source_map", None) is not None:+ abs_path = (+ str(Path(self._repo_root) / file_path)+ if getattr(self, "_repo_root", None) and not Path(file_path).is_absolute()+ else file_path+ )+ return read_source_text(file_path, abs_path, self._source_map)+ p = Path(file_path)+ if not p.is_absolute() and getattr(self, "_repo_root", None):+ p = Path(self._repo_root) / p+ if p.exists():+ return p.read_text(encoding="utf-8", errors="replace")+ except Exception as exc:+ logger.warning("read_file_text_failed", path=file_path, error=str(exc))+ return None+def _detect_unused_internals(self,dynamic_patterns: tuple[str, ...],diff --git a/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.pynew file mode 100644index 000000000..6a55fa9eb--- /dev/null+++ b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py@@ -0,0 +1,304 @@+"""AST helper for extracting guarded JSX component renders."""++from __future__ import annotations++from typing import Any++from tree_sitter import Language, Parser+++def extract_guarded_jsx_renders(+ file_path: str,+ src: str,+) -> list[tuple[str, str, str]]:+ """Extract (parent_fn_name, child_component_name, guard_prop_name) triples.++ Parses JS/TSX files and finds JSX component elements rendered behind binary (&&)+ or ternary prop guards.+ """+ if not file_path.endswith((".tsx", ".jsx", ".ts", ".js")):+ return []++ try:+ if file_path.endswith((".tsx", ".ts")):+ import tree_sitter_typescript as tstype++ lang = Language(tstype.language_tsx())+ else:+ import tree_sitter_javascript as tsjs++ lang = Language(tsjs.language())++ parser = Parser(lang)+ tree = parser.parse(src.encode("utf-8"))+ except Exception:+ return []++ code = src.encode("utf-8")+ results: list[tuple[str, str, str]] = []++ def _node_text(n: Any) -> str:+ return code[n.start_byte : n.end_byte].decode("utf-8", errors="replace")++ def _extract_prop_names(+ n: Any,+ local_vars: set[str] | None = None,+ param_props: set[str] | None = None,+ ) -> list[str]:+ if n.type == "parenthesized_expression":+ for c in n.children:+ if c.type not in ("(", ")"):+ return _extract_prop_names(c, local_vars, param_props)+ elif n.type == "member_expression":+ obj_node = n.children[0]+ obj_text = _node_text(obj_node)+ prop_text = None+ for c in n.children:+ if c.type == "property_identifier":+ prop_text = _node_text(c)+ if (+ obj_text in ("props", "this.props", "self.props")+ or obj_text.endswith(".props")+ ) and prop_text:+ return [prop_text]+ elif n.type == "identifier":+ name = _node_text(n)+ if name in ("true", "false", "undefined", "null"):+ return []+ if local_vars is not None and name in local_vars:+ return []+ if param_props is not None:+ return [name] if name in param_props else []+ return [name]+ elif n.type == "unary_expression":+ op = None+ operand = None+ for c in n.children:+ if c.type == "!":+ op = "!"+ else:+ operand = c+ if op == "!":+ if operand and operand.type == "unary_expression":+ sub_op = None+ sub_operand = None+ for sub in operand.children:+ if sub.type == "!":+ sub_op = "!"+ else:+ sub_operand = sub+ if sub_op == "!" and sub_operand:+ return _extract_prop_names(sub_operand, local_vars, param_props)+ return []+ elif n.type == "binary_expression":+ op = None+ left = None+ right = None+ for c in n.children:+ if c.type in ("&&", "===", "==", "!==", "!="):+ op = c.type+ elif left is None:+ left = c+ else:+ right = c+ if op in ("&&", "===", "==") and left and right:+ return _extract_prop_names(left, local_vars, param_props) + _extract_prop_names(+ right, local_vars, param_props+ )+ elif op in ("!==", "!=") and left and right:+ right_text = _node_text(right)+ left_text = _node_text(left)+ if right_text in ("undefined", "null", "false"):+ return _extract_prop_names(left, local_vars, param_props)+ elif left_text in ("undefined", "null", "false"):+ return _extract_prop_names(right, local_vars, param_props)+ return []++ def _find_jsx_targets(n: Any) -> list[str]:+ targets: list[str] = []+ if n.type in ("jsx_self_closing_element", "jsx_opening_element", "jsx_element"):+ if n.type == "jsx_element":+ for c in n.children:+ if c.type == "jsx_opening_element":+ targets.extend(_find_jsx_targets(c))+ else:+ for c in n.children:+ if c.type in ("identifier", "property_identifier"):+ name = _node_text(c)+ if name and name[0].isupper():+ targets.append(name)+ break+ elif c.type == "member_expression":+ prop_name = None+ for sub in c.children:+ if sub.type == "property_identifier":+ prop_name = _node_text(sub)+ if prop_name and prop_name[0].isupper():+ targets.append(prop_name)+ break+ else:+ for c in n.children:+ targets.extend(_find_jsx_targets(c))+ return targets++ def _extract_bound_names(n: Any) -> list[str]:+ names: list[str] = []+ if n.type in ("identifier", "shorthand_property_identifier_pattern"):+ names.append(_node_text(n))+ elif n.type in (+ "array_pattern",+ "object_pattern",+ "pair_pattern",+ "variable_declarator",+ "rest_pattern",+ ):+ for c in n.children:+ if c.type not in (":", "=", ",", "[", "]", "{", "}", "...", "var", "let", "const"):+ names.extend(_extract_bound_names(c))+ return names++ def _collect_module_local_vars(root: Any) -> set[str]:+ mod_vars: set[str] = set()+ for child in root.children:+ target_node = child+ if child.type == "export_statement":+ for c in child.children:+ if c.type in ("lexical_declaration", "variable_declaration"):+ target_node = c+ break+ if target_node.type in ("lexical_declaration", "variable_declaration"):+ for dec in target_node.children:+ if dec.type == "variable_declarator":+ for c in dec.children:+ if c.type in ("identifier", "array_pattern", "object_pattern"):+ mod_vars.update(_extract_bound_names(c))+ break+ return mod_vars++ module_vars = _collect_module_local_vars(tree.root_node)++ def _collect_function_param_props(fn_node: Any) -> set[str] | None:+ params_node = None+ for c in fn_node.children:+ if c.type in ("formal_parameters", "parameters"):+ params_node = c+ break+ if not params_node:+ return None++ param_props: set[str] = set()+ has_destructured_param = False++ for param in params_node.children:+ if param.type in ("(", ")", ",", ":"):+ continue+ p = param+ if p.type == "required_parameter":+ for child in p.children:+ if child.type in ("object_pattern", "identifier", "assignment_pattern"):+ p = child+ break+ if p.type == "assignment_pattern":+ for child in p.children:+ if child.type in ("object_pattern", "identifier"):+ p = child+ break++ if p.type == "object_pattern":+ has_destructured_param = True+ param_props.update(_extract_bound_names(p))++ return param_props if has_destructured_param else None++ def _collect_function_local_vars(fn_node: Any) -> set[str]:+ local_vars: set[str] = set(module_vars)++ def _scan(n: Any) -> None:+ if n != fn_node and n.type in (+ "function_declaration",+ "arrow_function",+ "function_expression",+ "method_definition",+ ):+ return+ if n.type == "variable_declarator":+ for c in n.children:+ if c.type in ("identifier", "array_pattern", "object_pattern"):+ local_vars.update(_extract_bound_names(c))+ break+ for c in n.children:+ _scan(c)++ _scan(fn_node)+ return local_vars++ def _walk(+ n: Any,+ current_fn: str | None = None,+ local_vars: set[str] | None = None,+ param_props: set[str] | None = None,+ ) -> None:+ current_local_vars = local_vars+ current_param_props = param_props+ if n.type in (+ "function_declaration",+ "arrow_function",+ "function_expression",+ "method_definition",+ ):+ fn_name = current_fn+ if n.type in ("function_declaration", "method_definition"):+ for c in n.children:+ if c.type in ("identifier", "property_identifier"):+ fn_name = _node_text(c)+ break+ elif n.parent and n.parent.type == "variable_declarator":+ for c in n.parent.children:+ if c.type == "identifier":+ fn_name = _node_text(c)+ break+ current_fn = fn_name or "Anonymous"+ current_local_vars = _collect_function_local_vars(n)+ current_param_props = _collect_function_param_props(n)++ if n.type == "binary_expression":+ op = None+ left = None+ right = None+ for c in n.children:+ if c.type == "&&":+ op = "&&"+ elif left is None:+ left = c+ else:+ right = c+ if op == "&&" and left and right:+ jsx_targets = _find_jsx_targets(right)+ if jsx_targets and current_fn:+ prop_names = _extract_prop_names(left, current_local_vars, current_param_props)+ for prop_name in prop_names:+ for target in jsx_targets:+ results.append((current_fn, target, prop_name))++ elif n.type == "ternary_expression":+ cond = None+ consequence = None+ for c in n.children:+ if c.type not in ("?", ":"):+ if cond is None:+ cond = c+ elif consequence is None:+ consequence = c+ if cond and consequence and current_fn:+ jsx_targets = _find_jsx_targets(consequence)+ if jsx_targets:+ prop_names = _extract_prop_names(cond, current_local_vars, current_param_props)+ for prop_name in prop_names:+ for target in jsx_targets:+ results.append((current_fn, target, prop_name))++ for child in n.children:+ _walk(child, current_fn, current_local_vars, current_param_props)++ _walk(tree.root_node)+ return resultsdiff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 8649e9a61..c4e3e3c29 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -215,6 +215,7 @@ class ResolvedCall:line: int # call site line number (for diagnostics)origin: ResolutionOrigin # which strategy below produced itedge_type: CallSiteEdgeType = "calls" # carried through from the CallSite+ supplied_props: frozenset[str] | None = None # prop names supplied in JSX element (None if unknown/spread)def _same_translation_unit(decl_file: str, def_file: str) -> bool:@@ -1035,10 +1036,15 @@ class CallResolver:# --- Method call with receiver: receiver.method() ---if call.receiver_name:- return self._resolve_member_call(file_path, call, caller_id)+ return self._with_props(self._resolve_member_call(file_path, call, caller_id), call)# --- Free function call: function() ---- return self._resolve_free_call(file_path, call, caller_id)+ return self._with_props(self._resolve_free_call(file_path, call, caller_id), call)++ def _with_props(self, res: ResolvedCall | None, call: CallSite) -> ResolvedCall | None:+ if res is not None and call.supplied_props is not None:+ return replace(res, supplied_props=call.supplied_props)+ return resdef _resolve_return_typed_chain(self,diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.pyindex 983c653d6..e6b2ba31a 100644--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py@@ -112,6 +112,9 @@ class RehydrateMixin:call_lines = edge.get("call_lines")if call_lines:edge_attrs["call_lines"] = list(call_lines)+ supplied_props = edge.get("supplied_props")+ if supplied_props is not None:+ edge_attrs["supplied_props"] = frozenset(supplied_props)graph.add_edge(source, target, **edge_attrs)edge_count += 1diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.pyindex 60ebda627..69abb9ae0 100644--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py@@ -572,7 +572,11 @@ class ResolveMixin:continueif not self._graph.has_edge(rc.caller_id, rc.callee_id):attrs = (- {"edge_type": "calls", "call_lines": [rc.line]}+ {+ "edge_type": "calls",+ "call_lines": [rc.line],+ "supplied_props": rc.supplied_props,+ }if rc.edge_type == "calls"else {"edge_type": "references"})@@ -608,6 +612,11 @@ class ResolveMixin:if rc.confidence > existing.get("confidence", 0):existing["confidence"] = rc.confidenceexisting["resolution_origin"] = rc.origin+ ex_props = existing.get("supplied_props")+ if ex_props is None or rc.supplied_props is None:+ existing["supplied_props"] = None+ else:+ existing["supplied_props"] = frozenset(ex_props | rc.supplied_props)if progress:progress.on_item_done("graph.calls")diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 6be328ad5..3a0018282 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -287,6 +287,7 @@ class CallSite:# and cpp has none -- a scoped call must stay on the free-call path.scope_name: str | None = Noneedge_type: CallSiteEdgeType = "calls" # see ``CallSiteEdgeType``+ supplied_props: set[str] | None = None # prop names supplied in JSX element (None if unknown/spread)HeritageKind = Literal["extends", "implements", "trait_impl", "mixin"]diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 18fca40a5..791cf682e 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -1895,6 +1895,24 @@ class ASTParser:arg_node = arg_nodes[0]arg_count = _count_arguments(arg_node)+ supplied_props: frozenset[str] | None = None+ if site_node.type in ("jsx_self_closing_element", "jsx_opening_element"):+ props_set: set[str] = set()+ has_spread = False+ for child in site_node.children:+ if child.type == "jsx_attribute":+ for sub in child.children:+ if sub.type in ("property_identifier", "identifier"):+ props_set.add(_node_text(sub, src))+ break+ elif child.type == "jsx_expression":+ for sub in child.children:+ if sub.type == "spread_element":+ has_spread = True+ break+ if not has_spread:+ supplied_props = frozenset(props_set)+caller_id = _find_enclosing_symbol(line, symbol_ranges)calls.append(@@ -1911,6 +1929,7 @@ class ASTParser:if site_node.type in config.reference_call_node_typeselse "calls"),+ supplied_props=supplied_props,))diff --git a/tests/unit/dead_code/_helpers.py b/tests/unit/dead_code/_helpers.pyindex 95f1cef1c..3f78b6dd4 100644--- a/tests/unit/dead_code/_helpers.py+++ b/tests/unit/dead_code/_helpers.py@@ -31,7 +31,14 @@ def _build_graph("""g = nx.DiGraph()for name, attrs in nodes.items():- attrs.setdefault("language", "python")+ if "language" not in attrs:+ name_lower = name.lower()+ if name_lower.endswith((".tsx", ".ts")):+ attrs["language"] = "typescript"+ elif name_lower.endswith((".jsx", ".js")):+ attrs["language"] = "javascript"+ else:+ attrs["language"] = "python"# Extract symbols before adding the file nodesym_list = attrs.pop("symbols", [])g.add_node(name, **attrs)diff --git a/tests/unit/dead_code/test_jsx_prop_guard_dead_code.py b/tests/unit/dead_code/test_jsx_prop_guard_dead_code.pynew file mode 100644index 000000000..97404de7c--- /dev/null+++ b/tests/unit/dead_code/test_jsx_prop_guard_dead_code.py@@ -0,0 +1,647 @@+"""Unit tests for JSX prop-guard dead code detection (#1554)."""++from __future__ import annotations++from repowise.core.analysis.dead_code import (+ DeadCodeAnalyzer,+ DeadCodeKind,+)+from tests.unit.dead_code._helpers import _build_graph+++def test_jsx_prop_guard_unsatisfied_reported(tmp_path):+ """Component B behind flag in Component A should be reported when A is rendered without flag."""+ a_content = """+function ComponentA(props) {+ return <div>{props.flag && <ComponentB />}</div>;+}+"""+ b_content = """+export function ComponentB() {+ return <div>Hello</div>;+}+"""+ app_content = """+function App() {+ return <ComponentA />;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ app_file = tmp_path / "App.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)+ app_file.write_text(app_content)++ g = _build_graph(+ nodes={+ str(app_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(app_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{app_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" in sym_names++ finding = next(f for f in unused if f.symbol_name == "ComponentB")+ assert finding.confidence == 0.4+ assert finding.safe_to_delete is False+ assert "flag" in finding.reason+++def test_jsx_prop_guard_satisfied_not_reported(tmp_path):+ """Component B should NOT be reported when Component A is rendered with flag."""+ a_content = """+function ComponentA(props) {+ return <div>{props.flag && <ComponentB />}</div>;+}+"""+ b_content = """+export function ComponentB() {+ return <div>Hello</div>;+}+"""+ app_content = """+function App() {+ return <ComponentA flag={true} />;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ app_file = tmp_path / "App.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)+ app_file.write_text(app_content)++ g = _build_graph(+ nodes={+ str(app_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(app_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{app_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset(["flag"])},+ ),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_jsx_prop_guard_spread_not_reported(tmp_path):+ """Component B should NOT be reported when Component A is rendered with spread props."""+ a_content = """+function ComponentA(props) {+ return <div>{props.flag && <ComponentB />}</div>;+}+"""+ b_content = """+export function ComponentB() {+ return <div>Hello</div>;+}+"""+ app_content = """+function App(props) {+ return <ComponentA {...props} />;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ app_file = tmp_path / "App.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)+ app_file.write_text(app_content)++ g = _build_graph(+ nodes={+ str(app_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(app_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{app_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": None},+ ),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_jsx_prop_guard_namespaced_reported(tmp_path):+ """Namespaced component <UI.Button /> behind prop guard should be detected."""+ a_content = """+function ComponentA(props) {+ return <div>{props.show && <UI.Button />}</div>;+}+"""+ b_content = """+export function Button() {+ return <button>Click</button>;+}+"""+ app_content = """+function App() {+ return <ComponentA />;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "Button.tsx"+ app_file = tmp_path / "App.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)+ app_file.write_text(app_content)++ g = _build_graph(+ nodes={+ str(app_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "Button", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(app_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(a_file), str(b_file), {"imported_names": ["Button"]}),+ (+ f"{app_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::Button",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "Button" in sym_names+++def test_jsx_prop_guard_negated_not_reported(tmp_path):+ """Component B behind !show guard renders when show is absent and should NOT be reported as dead."""+ a_content = """+function ComponentA(props) {+ return <div>{!props.show && <ComponentB />}</div>;+}+"""+ b_content = """+export function ComponentB() {+ return <div>Hello</div>;+}+"""+ app_content = """+function App() {+ return <ComponentA />;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ app_file = tmp_path / "App.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)+ app_file.write_text(app_content)++ g = _build_graph(+ nodes={+ str(app_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(app_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{app_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_jsx_prop_guard_root_component_not_reported(tmp_path):+ """Component B behind guard in root component (no incoming callers) should NOT be falsely reported."""+ a_content = """+function ComponentA(props) {+ return <div>{props.flag && <ComponentB />}</div>;+}+"""+ b_content = """+export function ComponentB() {+ return <div>Hello</div>;+}+"""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"++ a_file.write_text(a_content)+ b_file.write_text(b_content)++ g = _build_graph(+ nodes={+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_read_file_text_relative_path(tmp_path):+ """_read_file_text should resolve relative paths when repo_root is provided."""+ sub_dir = tmp_path / "src"+ sub_dir.mkdir()+ rel_file = sub_dir / "Test.tsx"+ rel_file.write_text("const x = 1;")++ g = _build_graph(nodes={})+ analyzer = DeadCodeAnalyzer(g, repo_root=tmp_path)+ content = analyzer._read_file_text("src/Test.tsx")+ assert content == "const x = 1;"+++def test_jsx_prop_guard_local_state_not_reported(tmp_path):+ """Component rendered behind local state (const/let/useState) guard should NOT be reported as dead code."""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ c_file = tmp_path / "App.tsx"++ a_file.write_text(+ "import React, { useState } from 'react';\n"+ "import { ComponentB } from './ComponentB';\n"+ "export function ComponentA() {\n"+ " const [isExpanded, setIsExpanded] = useState(false);\n"+ " return <div>{isExpanded && <ComponentB />}</div>;\n"+ "}\n"+ )+ b_file.write_text("export function ComponentB() { return <div>B</div>; }\n")+ c_file.write_text(+ "import { ComponentA } from './ComponentA';\n"+ "export function App() { return <ComponentA />; }\n"+ )++ g = _build_graph(+ nodes={+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ str(c_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (str(c_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{c_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_jsx_prop_guard_destructured_props_local_state_ignored(tmp_path):+ """Local state in a component with destructured props should NOT be extracted as a prop guard."""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ c_file = tmp_path / "App.tsx"++ a_file.write_text(+ "import React, { useState } from 'react';\n"+ "import { ComponentB } from './ComponentB';\n"+ "export function ComponentA({ showExtra }) {\n"+ " const [isExpanded, setIsExpanded] = useState(false);\n"+ " return <div>{isExpanded && <ComponentB />}</div>;\n"+ "}\n"+ )+ b_file.write_text("export function ComponentB() { return <div>B</div>; }\n")+ c_file.write_text(+ "import { ComponentA } from './ComponentA';\n"+ "export function App() { return <ComponentA showExtra={true} />; }\n"+ )++ g = _build_graph(+ nodes={+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ str(c_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (str(c_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{c_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset(["showExtra"])},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names+++def test_jsx_prop_guard_module_constant_ignored(tmp_path):+ """Module-level constants should NOT be extracted as prop guards."""+ a_file = tmp_path / "ComponentA.tsx"+ b_file = tmp_path / "ComponentB.tsx"+ c_file = tmp_path / "App.tsx"++ a_file.write_text(+ "import React from 'react';\n"+ "import { ComponentB } from './ComponentB';\n"+ "const SHOW_DEBUG = true;\n"+ "export function ComponentA() {\n"+ " return <div>{SHOW_DEBUG && <ComponentB />}</div>;\n"+ "}\n"+ )+ b_file.write_text("export function ComponentB() { return <div>B</div>; }\n")+ c_file.write_text(+ "import { ComponentA } from './ComponentA';\n"+ "export function App() { return <ComponentA />;\n"+ )++ g = _build_graph(+ nodes={+ str(a_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentA", "kind": "function", "visibility": "public"}],+ },+ str(b_file): {+ "is_entry_point": False,+ "is_test": False,+ "symbols": [{"name": "ComponentB", "kind": "function", "visibility": "public"}],+ },+ str(c_file): {+ "is_entry_point": True,+ "is_test": False,+ "symbols": [{"name": "App", "kind": "function", "visibility": "public"}],+ },+ },+ edges=[+ (str(a_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (str(c_file), str(a_file), {"imported_names": ["ComponentA"]}),+ (str(c_file), str(b_file), {"imported_names": ["ComponentB"]}),+ (+ f"{a_file}::ComponentA",+ f"{b_file}::ComponentB",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ (+ f"{c_file}::App",+ f"{a_file}::ComponentA",+ {"edge_type": "calls", "confidence": 0.95, "supplied_props": frozenset()},+ ),+ ],+ )++ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ }+ )++ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+ sym_names = [f.symbol_name for f in unused]+ assert "ComponentB" not in sym_names++++diff --git a/tests/unit/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.pyindex be27fe49b..b81695eb0 100644--- a/tests/unit/ingestion/test_graph_rehydrate.py+++ b/tests/unit/ingestion/test_graph_rehydrate.py@@ -174,3 +174,19 @@ def test_rehydrate_without_metrics_falls_back_to_recompute():# Recompute on the rehydrated structure still equals the original.assert hydrated.pagerank() == original.pagerank()assert hydrated.in_degree()["c.py"] == 2+++def test_supplied_props_survives_rehydration():+ """An edge's supplied_props must outlive the process that resolved it."""+ original = _build_sample()+ nodes, edges = _serialize(original)+ edges[0] = {**edges[0], "edge_type": "calls", "supplied_props": ["showBanner", "isLoaded"]}++ hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())+ graph = hydrated.graph()++ stamped = graph[edges[0]["source_node_id"]][edges[0]["target_node_id"]]+ assert stamped["supplied_props"] == frozenset(["showBanner", "isLoaded"])+ for e in edges[1:]:+ assert "supplied_props" not in graph[e["source_node_id"]][e["target_node_id"]]+