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
refactor(refactoring): flatten the plan detectors this week made too deep (#3550)
Raghav Chamadiya23f3825fc684
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 6f665ca3b..e90f48580 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -272,9 +272,9 @@ def find_extractions():continuereason = exception_flow_refusal(analysis.cfg, s, e, reads, def_lines)+ if reason is not None and refused is not None:+ refused.add(reason)if reason is not None:- if refused is not None:- refused.add(reason)continueuses, assigns = _receiver_facts(receiver, pre, i, j, _count_in(free_writes, s, e))out.append(diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex 546a54cf4..88d6aa051 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -191,90 +191,118 @@ class ExtractMethodDetector(RefactoringDetector):files: dict[str, Any] = {}# Source order, so the first of two colliding plans keeps the name.for analysis in sorted(analyses, key=lambda a: (a.start_line, a.end_line)):- matched = self._findings_for(analysis, ctx.findings)- if not matched:- # Only suggest where a method biomarker actually fired.- continue- if jsx_plumbing_dominates(analysis.fn_node, lmap):- continue- if analysis.fn_node is not None and declarative_flat(- analysis.fn_node, lmap, {p.name for p in analysis.def_use.params}, ctx.language- ):- _mark_refused(matched, "declarative_flat")- continue- markers = {getattr(f, "biomarker_type", "") for f in matched}- fn_node = analysis.fn_node- receiver = dialect.receiver(fn_node, lmap) if dialect and fn_node else None- # The slicer's per-block walk, read again by a staged plan.- prefixes: dict[int, Any] = {}- refused: set[str] = set()- candidates = find_extractions(analysis, lmap, receiver, prefixes, refused)- _mark_stage_refused(matched, frozenset(refused))- best = _choose(analysis, candidates, markers)- staged = _staged(analysis, best, lmap, receiver, ctx.language, matched, prefixes)- scope = _scope(fn_node, files) if staged is not None or best is not None else None- if staged is not None:- split = self._staged_suggestion(ctx, analysis, staged, matched, names, receiver)- if anchor_plan(split.plan, scope):- out.append(split)- continue- if best is None:- # Nothing to fall back to from a split no text anchors.- if staged is not None:- _mark_refused(matched, "span_unanchored")- continue- impact, share, source = self._impact_for(analysis, best, matched)- name = render.private_name(- ctx.language,- names.claim_first(- analysis,- helper_names(analysis, best, lmap, ctx.language, names.imports(fn_node)),- ),- )- async_fields = _async_fields(analysis, best, lmap, ctx.language)- symbol = _render_fields(- analysis,- best,- dialect,- ctx.language,- name,- _symbol_fields(best, receiver),- async_host=async_fields.get("async_host", True),- )- _serve_anchored(- out,- RefactoringSuggestion(- refactoring_type=self.name,- file_path=ctx.file_path,- target_symbol=analysis.name,- line_start=analysis.start_line,- line_end=analysis.end_line,- plan={- "span": {"start": best.start_line, "end": best.end_line},- "params": list(best.params),- "returns": list(best.returns),- "suggested_name": name,- **async_fields,- **symbol,- },- evidence={- "slice_nloc": best.slice_nloc,- "ccn_removed": best.ccn_removed,- },- impact_delta=round(float(impact), 3),- effort_bucket=effort_bucket(best.slice_nloc),- blast_radius={"scope": "local"},- confidence=self._confidence(best, share),- source_biomarker=source,- ),- matched,- scope,- )+ matched = self._eligible_findings(ctx, analysis, lmap)+ if matched:+ self._suggest(ctx, analysis, matched, lmap, dialect, names, files, out)# Stable order: biggest recovery first, then symbol, then span start.out.sort(key=lambda s: (-s.impact_delta, s.target_symbol, s.line_start or 0))return out+ def _eligible_findings(+ self, ctx: RefactoringContext, analysis: FunctionAnalysis, lmap: LanguageNodeMap+ ) -> list[Any]:+ """The findings flagging *analysis* when it may be offered a plan, else+ empty: a JSX plumbing component gets none, nor (refused) a flat record+ builder."""+ # Only suggest where a method biomarker actually fired.+ matched = self._findings_for(analysis, ctx.findings)+ if not matched or jsx_plumbing_dominates(analysis.fn_node, lmap):+ return []+ if analysis.fn_node is not None and declarative_flat(+ analysis.fn_node, lmap, {p.name for p in analysis.def_use.params}, ctx.language+ ):+ _mark_refused(matched, "declarative_flat")+ return []+ return matched++ def _suggest(+ self,+ ctx: RefactoringContext,+ analysis: FunctionAnalysis,+ matched: list[Any],+ lmap: LanguageNodeMap,+ dialect: BaseDefUseDialect | None,+ names: ScopeNames,+ files: dict[str, Any],+ out: list[RefactoringSuggestion],+ ) -> None:+ """Add *analysis*'s plan to *out*: the staged split when one is anchored,+ else the best single span; why none was offered goes on *matched*."""+ markers = {getattr(f, "biomarker_type", "") for f in matched}+ fn_node = analysis.fn_node+ receiver = dialect.receiver(fn_node, lmap) if dialect and fn_node else None+ # The slicer's per-block walk, read again by a staged plan.+ prefixes: dict[int, Any] = {}+ refused: set[str] = set()+ candidates = find_extractions(analysis, lmap, receiver, prefixes, refused)+ _mark_stage_refused(matched, frozenset(refused))+ best = _choose(analysis, candidates, markers)+ staged = _staged(analysis, best, lmap, receiver, ctx.language, matched, prefixes)+ scope = _scope(fn_node, files) if staged is not None or best is not None else None+ if staged is not None:+ split = self._staged_suggestion(ctx, analysis, staged, matched, names, receiver)+ if anchor_plan(split.plan, scope):+ out.append(split)+ return+ if best is None:+ # Nothing to fall back to from a split no text anchors.+ if staged is not None:+ _mark_refused(matched, "span_unanchored")+ return+ name = render.private_name(+ ctx.language,+ names.claim_first(+ analysis,+ helper_names(analysis, best, lmap, ctx.language, names.imports(fn_node)),+ ),+ )+ async_fields = _async_fields(analysis, best, lmap, ctx.language)+ symbol = _render_fields(+ analysis,+ best,+ dialect,+ ctx.language,+ name,+ _symbol_fields(best, receiver),+ async_host=async_fields.get("async_host", True),+ )+ fields = {"suggested_name": name, **async_fields, **symbol}+ _serve_anchored(out, self._single_suggestion(ctx, analysis, best, matched, fields), matched, scope)++ def _single_suggestion(+ self,+ ctx: RefactoringContext,+ analysis: FunctionAnalysis,+ best: Extraction,+ matched: list[Any],+ fields: dict[str, Any],+ ) -> RefactoringSuggestion:+ """The plan lifting *best*, its rendered *fields* after the span."""+ impact, share, source = self._impact_for(analysis, best, matched)+ return RefactoringSuggestion(+ refactoring_type=self.name,+ file_path=ctx.file_path,+ target_symbol=analysis.name,+ line_start=analysis.start_line,+ line_end=analysis.end_line,+ plan={+ "span": {"start": best.start_line, "end": best.end_line},+ "params": list(best.params),+ "returns": list(best.returns),+ **fields,+ },+ evidence={+ "slice_nloc": best.slice_nloc,+ "ccn_removed": best.ccn_removed,+ },+ impact_delta=round(float(impact), 3),+ effort_bucket=effort_bucket(best.slice_nloc),+ blast_radius={"scope": "local"},+ confidence=self._confidence(best, share),+ source_biomarker=source,+ )+def _staged_suggestion(self,ctx: RefactoringContext,diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py b/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.pyindex e03db045f..a56de1e50 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py@@ -61,16 +61,29 @@ def narrowings(if node.parent.type in lmap.block_kinds:sib = node.prev_named_siblingwhile sib is not None:- line = sib.start_point[0] + 1- for name, drops in _guard_tests(sib, lmap).items():- rebound = any(sib.end_point[0] + 1 < ln <= end for ln in def_lines.get(name, ()))- if name in names and name not in out and not rebound:- out[name] = Narrowing(line, drops)+ _add_guard(sib, lmap, end, names, def_lines, out)sib = sib.prev_named_siblingnode = node.parentreturn out+def _add_guard(+ sib: Node,+ lmap: LanguageNodeMap,+ end: int,+ names: set[str],+ def_lines: dict[str, list[int]],+ out: dict[str, Narrowing],+) -> None:+ """Record in *out* each name in *names* guard *sib* narrows that has no+ nearer guard yet and nothing rebinds before line *end*."""+ line = sib.start_point[0] + 1+ for name, drops in _guard_tests(sib, lmap).items():+ rebound = any(sib.end_point[0] + 1 < ln <= end for ln in def_lines.get(name, ()))+ if name in names and name not in out and not rebound:+ out[name] = Narrowing(line, drops)++def narrowed(declared: str, drops: frozenset[str]) -> str | None:"""*declared* without the union arms in *drops*; None when nothing is left."""arms = union_arms(declared)