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(refactoring): suppress the plans the gates cannot prove behaviour-preserving (#1984)
Raghav Chamadiya3d15548aaa3c
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex d3f577b65..e0fdb486c 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -37,7 +37,7 @@ one**, and produces stable-sorted, deterministic output.| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. || **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. || **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |-| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify; IN/OUT comes from liveness over the def/use facts, so the suggested helper is behavior-preserving by construction. |+| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify, and IN/OUT comes from liveness over the def/use facts. A span is offered only when the gate can prove it behavior-preserving: every returned value must be written on every path through the span, and a span nested in a loop must carry no state between iterations and must not mutate what the loop iterates. What the gate cannot prove is suppressed, not demoted, so the layer under-reports rather than suggest a rewrite that changes behavior. || **Performance Fix** | A safe shared intervention, affected call sites, and caller-to-sink paths for one causal performance opportunity. | The call-graph opportunity service groups raw findings by stable cause, boundary and context, then emits only supported strategies. Findings with no coherent safe intervention remain visible in Code Health without a plan. |The algorithms are derived from public academic literature (Fokaefs-Tsantalis@@ -61,7 +61,7 @@ web).|-------|---------|| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` \| `extract_method` \| `performance_fix` || `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |-| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. |+| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. Names are omitted rather than invented: `suggested_name` and a group's `name` / `suggested_file` are `null` whenever no fact anchors a name, and `suggested_site.directory` is `null` unless an occurrence actually lives in that directory. || `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. || `impact_delta` | The defect-health score the refactoring would recover; `0` for graph-native and performance plans. Their canonical `benefit` comes from detector-native evidence instead. || `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. |diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.pyindex f50adedf6..9c09c6b5c 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py@@ -370,7 +370,7 @@ def _render_split_file_plans_console(plans: list[dict]) -> None:)for i, g in enumerate(groups, 1):console.print(- f" [bold]{i}.[/bold] [green]{g.get('suggested_file')}[/green]: "+ f" [bold]{i}.[/bold] [green]{g.get('suggested_file') or '(unnamed)'}[/green]: "f"{', '.join(g.get('symbols', []))}")residual = pl.get("residual")@@ -392,7 +392,8 @@ def _render_split_file_plans_md(plans: list[dict]) -> None:f"modularity {ev.get('modularity')}, split into {len(groups)} files:")for i, g in enumerate(groups, 1):- click.echo(f" {i}. `{g.get('suggested_file')}`: {', '.join(g.get('symbols', []))}")+ name = g.get("suggested_file") or "(unnamed)"+ click.echo(f" {i}. `{name}`: {', '.join(g.get('symbols', []))}")residual = pl.get("residual")if residual and residual.get("symbols"):click.echo(f" - core (shared): {', '.join(residual['symbols'])}")diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex c92a24956..a6341d402 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -115,7 +115,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[out: list[Extraction] = []evaluated = 0- for block in _all_blocks(fn_node, lmap.block_kinds, scope_kinds):+ for block, loop in _all_blocks(fn_node, lmap.block_kinds, scope_kinds, lmap.loop_kinds):stmts = block.named_childrenn = len(stmts)is_body = block.id == body_container.id@@ -161,6 +161,12 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[params, returns = _infer_in_out(def_lines, use_lines, s, e)if len(params) > _MAX_PARAMS or len(returns) > _MAX_RETURNS:continue+ if not _outs_definitely_assigned(span, returns, def_lines, lmap):+ continue+ if loop is not None and not _loop_carry_free(+ span, loop, s, e, def_lines, use_lines, lmap+ ):+ continueout.append(Extraction(start_line=s,@@ -237,6 +243,268 @@ def _infer_in_out(return tuple(params), tuple(returns)+def _outs_definitely_assigned(+ span: list[Node],+ returns: tuple[str, ...],+ def_lines: dict[str, list[int]],+ lmap: LanguageNodeMap,+) -> bool:+ """True when every OUT variable is written on *every* path through the span.++ A conditionally written OUT is the unsound case line-based liveness cannot+ see: the helper returns the unwritten value on the paths that skip the+ write, and the caller's assignment then clobbers the live one. The proof+ needs branch structure, so it runs structurally here and the span is+ refused whenever the proof does not go through.+ """+ return all(_stmts_assign(span, var, def_lines.get(var, []), lmap) for var in returns)+++def _stmts_assign(stmts: list[Node], var: str, defs: list[int], lmap: LanguageNodeMap) -> bool:+ """True when *stmts* writes *var* on every path through them."""+ return any(_stmt_assigns(st, var, defs, lmap) for st in stmts)+++def _stmt_assigns(st: Node, var: str, defs: list[int], lmap: LanguageNodeMap) -> bool:+ """True only when *st* is proved to write *var* however it is entered.++ Positive proof only: a statement kind this cannot classify returns False.+ Defaulting to True would let any statement sharing a line with a+ conditional write stand in as the proof.+ """+ lo = st.start_point[0] + 1+ hi = st.end_point[0] + 1+ if not any(lo <= d <= hi for d in defs):+ return False+ if _is_conditional(st, lmap):+ return _conditional_assigns(st, var, defs, lmap)+ if st.type in lmap.block_kinds:+ container = _unwrap_container(st, lmap.block_kinds)+ return _stmts_assign(container.named_children, var, defs, lmap)+ if st.type in lmap.with_kinds or st.type in lmap.statement_wrapper_kinds:+ return _stmts_assign(list(st.named_children), var, defs, lmap)+ return _unconditional_write(st, var, lmap)+++def _unconditional_write(st: Node, var: str, lmap: LanguageNodeMap) -> bool:+ """True when *st* contains a write to *var* no branch or loop guards.++ The walk stops at any control container (a loop body may run zero times, a+ branch arm may not be taken, a catch arm may not fire) and at nested+ scopes, so only writes on the statement's own straight-line path count.+ """+ write_kinds = lmap.assignment_kinds | lmap.augmented_assign_kinds | lmap.local_decl_kinds+ if not write_kinds:+ return False+ barriers = (+ lmap.loop_kinds+ | lmap.try_kinds+ | lmap.catch_kinds+ | lmap.switch_kinds+ | lmap.case_kinds+ | lmap.branch_kinds+ | lmap.if_kinds+ | lmap.function_kinds+ | lmap.lambda_kinds+ )+ if st.type in barriers:+ return False+ stack = [st]+ while stack:+ node = stack.pop()+ if node.id != st.id and node.type in barriers:+ continue+ if node.type in write_kinds and _writes_var(node, var):+ return True+ stack.extend(node.children)+ return False+++def _writes_var(node: Node, var: str) -> bool:+ """True when *var* is on the binding side of this write node."""+ for field in ("left", "pattern", "declarator", "name"):+ target = node.child_by_field_name(field)+ if target is not None:+ return var in _identifiers(target)+ return var in _identifiers(node)+++def _is_conditional(node: Node, lmap: LanguageNodeMap) -> bool:+ return node.type in lmap.if_kinds or (+ node.type in lmap.branch_kinds and node.child_by_field_name("condition") is not None+ )+++def _conditional_assigns(node: Node, var: str, defs: list[int], lmap: LanguageNodeMap) -> bool:+ """True when a conditional chain is exhaustive and every arm writes *var*.++ Two chain shapes. Python flattens ``elif``/``else`` into repeated+ ``alternative`` fields on one ``if``, so the terminal else is a sibling of+ the chained arms. The C family nests instead: the single ``alternative`` is+ another ``if``, whose own else ends the chain. Both must be exhaustive.+ """+ consequence = node.child_by_field_name("consequence") or node.child_by_field_name("body")+ if consequence is None:+ return False+ alternatives = list(node.children_by_field_name("alternative"))+ if not alternatives:+ return False # no else at all: some path skips the write+ if not _branch_assigns(consequence, var, defs, lmap):+ return False+ for alt in alternatives:+ if _is_conditional(alt, lmap):+ # Nested chain (C family): it carries the chain's terminal else.+ if len(alternatives) == 1:+ return _conditional_assigns(alt, var, defs, lmap)+ # Flattened chain (Python's ``elif``): the else is a sibling below.+ arm = alt.child_by_field_name("consequence") or alt.child_by_field_name("body")+ if arm is None or not _branch_assigns(arm, var, defs, lmap):+ return False+ elif not _branch_assigns(alt, var, defs, lmap):+ return False+ return any(not _is_conditional(alt, lmap) for alt in alternatives)+++def _branch_assigns(node: Node, var: str, defs: list[int], lmap: LanguageNodeMap) -> bool:+ if _is_conditional(node, lmap):+ return _conditional_assigns(node, var, defs, lmap)+ if node.type in lmap.block_kinds:+ container = _unwrap_container(node, lmap.block_kinds)+ return _stmts_assign(container.named_children, var, defs, lmap)+ return _stmts_assign(list(node.named_children), var, defs, lmap)+++def _loop_carry_free(+ span: list[Node],+ loop: Node,+ s: int,+ e: int,+ def_lines: dict[str, list[int]],+ use_lines: dict[str, list[int]],+ lmap: LanguageNodeMap,+) -> bool:+ """True when a span nested in *loop* carries no state between iterations.++ Two shapes are refused. A variable the span writes that is also read+ earlier in the same loop is loop-carried: the helper would see this+ iteration's value where the loop sees the previous one. And a call on a+ name the loop header reads mutates the state the loop iterates over+ (``entries.remove(entry)`` inside ``for entry in entries``), which an+ IN/OUT signature cannot express at all.+ """+ loop_start = loop.start_point[0] + 1+ for var, lines in def_lines.items():+ if not any(s <= ln <= e for ln in lines):+ continue+ if any(loop_start <= ln < s for ln in use_lines.get(var, [])):+ return False++ carried = _loop_header_names(loop, lmap)+ if not carried:+ return True+ scope_kinds = lmap.function_kinds | lmap.lambda_kinds+ for st in span:+ for call in _descend(st, lmap.call_kinds, scope_kinds):+ callee = call.child_by_field_name("function")+ if callee is None:+ named = call.named_children+ callee = named[0] if named else None+ root = _receiver_root(callee) if callee is not None else None+ if root is not None and root in carried:+ return False+ return True+++def _receiver_root(node: Node) -> str | None:+ """The base name a call is made on: ``entries`` in ``entries.remove(x)``.++ Only the root counts. Matching any name in the callee read+ ``existing.pages.push(page)`` as touching the ``pages`` the loop iterates,+ when the receiver is ``existing`` and the collision is in a member name.+ """+ cur = node+ while True:+ nxt = None+ for field in ("object", "operand", "value", "argument", "function"):+ child = cur.child_by_field_name(field)+ if child is not None:+ nxt = child+ break+ if nxt is None:+ break+ cur = nxt+ if not cur.children and cur.type.endswith("identifier"):+ text = cur.text+ return text.decode("utf-8", "replace") if text else None+ return None+++# Fields a loop header binds through. Read structurally: a line-range test+# cannot tell the header's binder from a variable reassigned on the body's+# first line, and getting that wrong drops the iterated collection out of the+# carried set, which is exactly the name the mutation check exists to catch.+_BINDER_FIELDS = ("left", "pattern", "declarator", "name")+++def _loop_header_names(loop: Node, lmap: LanguageNodeMap) -> set[str]:+ """Names the loop header reads, minus the ones it binds (the loop variable)."""+ body = loop.child_by_field_name("body")+ names: set[str] = set()+ # The binder is a field of the loop itself in most grammars, and of a+ # header clause it wraps in Go's ``range``.+ bound: set[str] = _binder_names(loop)+ for child in loop.children:+ if body is not None and child.id == body.id:+ continue+ names |= _identifiers(child)+ bound |= _binder_names(child)+ return names - bound+++def _binder_names(node: Node) -> set[str]:+ """Identifiers in the binding position of *node* or of a header clause it+ wraps (Go nests its range clause inside the ``for``)."""+ out: set[str] = set()+ for field in _BINDER_FIELDS:+ target = node.child_by_field_name(field)+ if target is not None:+ out |= _identifiers(target)+ if not out:+ for child in node.named_children:+ for field in _BINDER_FIELDS:+ target = child.child_by_field_name(field)+ if target is not None:+ out |= _identifiers(target)+ return out+++def _identifiers(node: Node) -> set[str]:+ out: set[str] = set()+ stack = [node]+ while stack:+ cur = stack.pop()+ if not cur.children and cur.type.endswith("identifier"):+ text = cur.text+ if text:+ out.add(text.decode("utf-8", "replace"))+ stack.extend(cur.children)+ return out+++def _descend(root: Node, kinds: frozenset[str], skip: frozenset[str]) -> list[Node]:+ found: list[Node] = []+ stack = [root]+ while stack:+ cur = stack.pop()+ if cur.type in kinds:+ found.append(cur)+ for child in cur.children:+ if child.type in skip:+ continue+ stack.append(child)+ return found++def _unwrap_container(node: Node, block_kinds: frozenset[str]) -> Node:"""Descend through a single nested statement-container (Go's``block`` -> ``statement_list``) to the node whose named children are the@@ -251,23 +519,31 @@ def _unwrap_container(node: Node, block_kinds: frozenset[str]) -> Node:def _all_blocks(- fn_node: Node, block_kinds: frozenset[str], scope_kinds: frozenset[str]-) -> list[Node]:+ fn_node: Node,+ block_kinds: frozenset[str],+ scope_kinds: frozenset[str],+ loop_kinds: frozenset[str],+) -> list[tuple[Node, Node | None]]:"""Every statement container in the function (body + nested), excluding the- bodies of nested functions / lambdas."""+ bodies of nested functions / lambdas, each paired with the innermost loop+ enclosing it (``None`` at loop-free depth)."""body = fn_node.child_by_field_name("body")if body is None:return []- blocks: list[Node] = []- stack: list[Node] = [body]+ blocks: list[tuple[Node, Node | None]] = []+ stack: list[tuple[Node, Node | None]] = [(body, None)]while stack:- node = stack.pop()+ node, loop = stack.pop()if node.type in block_kinds:- blocks.append(node)+ blocks.append((node, loop))+ is_loop = node.type in loop_kinds+ body = node.child_by_field_name("body") if is_loop else Nonefor child in node.children:if child.type in scope_kinds:continue- stack.append(child)+ # Only the loop's body repeats. A ``for ... else`` clause runs once.+ in_loop = node if (is_loop and body is not None and child.id == body.id) else loop+ stack.append((child, in_loop))return blocksdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.pyindex 73ff38852..d663ceeee 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py@@ -43,7 +43,6 @@ from typing import Anyfrom ....test_paths import is_test_related_pathfrom .models import RefactoringContext, RefactoringSuggestion-from .naming import identifier_slugfrom .registry import RefactoringDetector, effort_bucket, register# The biomarker this detector answers — the recovered impact is read off it.@@ -106,12 +105,24 @@ _FIELD_CTOR = re.compile(r"^\s*(dataclasses\.|attr\.|attrs\.|pydantic\.|msgspec\.)?"r"(field|Field|ib|attrib|mapped_column|Column|relationship)\s*\(",)+# Table-level declarative constructs. Same closed-vocabulary posture as+# ``_FIELD_CTOR``: these are schema, never behaviour, and a run of them was the+# other half of the ORM boilerplate that reached the top of the plan board.+_TABLE_DECL = re.compile(+ r"^\s*(UniqueConstraint|Index|CheckConstraint|ForeignKeyConstraint|PrimaryKeyConstraint)\s*\(",+)+# A dunder class attribute (``__table_args__``, ``__tablename__``, ``__all__``)+# configures the class; it does not compute.+_DUNDER_ATTR = re.compile(r"^\s*__\w+__\s*=")_DECL_LINE = re.compile(r"""^\s*([\w.\[\]"']+ \s* : \s* [^=]+ # annotated, no default: name: type| [\w]+ \s* ,? # bare parameter / enum member| [)\]}]\s* [:,]? \s* (->.*)? :? \s* # a closer, with or without a return type| (async\s+)?(def|function|fn|func|class|interface|type|struct)\s+[\w<>]+\s*[(<{:]?\s*+ | (async\s+)?(def|function|fn|func|class|interface|type|struct)\s+[\w<>]+\s*+ \( (?: [^()] | \([^()]*\) )* \) # its parameter list, and nothing past it+ \s* (->[^:{;]*)? \s* [:{]? \s* # a signature joined back whole| @[\w.]+ \s* \(? # decorator / annotation)$""",re.VERBOSE,@@ -122,6 +133,47 @@ _CONTROL_FLOW = re.compile()+_STRING_LITERAL = re.compile(r"\"([^\"\\]|\\.)*\"|'([^'\\]|\\.)*'")+_TRAILING_COMMENT = re.compile(r"(#|//).*$")+++def _logical_lines(lines: list[str]) -> list[str]:+ """Join bracket continuations so one declaration reads as one line.++ ``user_id: Mapped[str] = mapped_column(\n String(32), nullable=False\n)``+ is one field declaration. Classified line by line, its middle line matches+ no declaration shape and the whole block reads as behaviour -- which is how+ runs of ORM columns reached the top of the plan board.+ """+ out: list[str] = []+ pending = ""+ depth = 0+ for line in lines:+ pending = f"{pending} {line.strip()}".strip() if pending else line.strip()+ depth += _continuation_depth(line)+ if depth <= 0:+ out.append(pending)+ pending = ""+ depth = 0+ if pending:+ out.append(pending)+ return out+++def _continuation_depth(line: str) -> int:+ """Net unclosed ``(``/``[`` on *line*, ignoring strings and comments.++ Braces are excluded deliberately: in a brace language ``{`` opens a body,+ not a continuation, and counting it welded whole function bodies into one+ line, which then read as a declaration. A bracket inside a string or a+ trailing comment is text, and counting those desynchronised the depth and+ absorbed the statements that followed.+ """+ bare = _STRING_LITERAL.sub("", line)+ bare = _TRAILING_COMMENT.sub("", bare)+ return sum(bare.count(o) - bare.count(c) for o, c in ("()", "[]"))++def _code_lines(block: list[str]) -> list[str]:"""*block* minus blanks and whole-line comments.@@ -169,7 +221,7 @@ def _is_declaration_only(block: list[str]) -> bool:and the defect here is the advice, not the measurement. The block stillcounts as duplication; it just no longer produces a plan to extract it."""- lines = _code_lines(block)+ lines = _logical_lines(_code_lines(block))if not lines:return Truefor line in lines:@@ -177,6 +229,8 @@ def _is_declaration_only(block: list[str]) -> bool:return Falseif line.startswith(_IMPORT_PREFIXES) or line in ("(", ")", "):", "}", "];", "{"):continue+ if _TABLE_DECL.match(line) or _DUNDER_ATTR.match(line):+ continueif _DECL_LINE.match(line):continue# An assignment is a declaration only by what it assigns. A constant@@ -257,6 +311,53 @@ class _Block:self.occurrences.add((pair.file_a, pair.a_start_line, pair.a_end_line))+def _symbol_spans(graph: Any, file_path: str, cache: dict[str, list[tuple[int, int]]]) -> list[tuple[int, int]]:+ """Declaration spans defined in *file_path*, via ``defines`` edges.++ Empty when the graph has no node for the file, which the caller reads as+ "no evidence" and abstains on rather than guessing.+ """+ hit = cache.get(file_path)+ if hit is not None:+ return hit+ spans: list[tuple[int, int]] = []+ if graph is not None and file_path in graph:+ for _u, target, data in graph.out_edges(file_path, data=True):+ if data.get("edge_type") != "defines":+ continue+ node = graph.nodes[target]+ if node.get("node_type") != "symbol" or node.get("kind") == "module":+ continue+ start, end = node.get("start_line"), node.get("end_line")+ if isinstance(start, int) and isinstance(end, int) and end >= start:+ spans.append((start, end))+ cache[file_path] = spans+ return spans+++def _within_one_declaration(+ occurrence: tuple[str, int, int], graph: Any, cache: dict[str, list[tuple[int, int]]]+) -> bool:+ """True when the occurrence sits inside a single declaration.++ Every symbol whose span it touches must also contain it. That admits a run+ of top-level statements and a block nested in a function or class (a method+ inside its class contains it twice over), and rejects both a span that ends+ part-way into the next declaration and one that swallows whole declarations.+ A helper function cannot be lifted out of either.+ """+ file_path, start, end = occurrence+ spans = _symbol_spans(graph, file_path, cache)+ if not spans:+ return True # no symbol facts for this file: nothing to gate on+ for sym_start, sym_end in spans:+ if sym_end < start or sym_start > end:+ continue+ if not (sym_start <= start and end <= sym_end):+ return False+ return True++@registerclass ExtractHelperDetector(RefactoringDetector):name = "extract_helper"@@ -270,9 +371,10 @@ class ExtractHelperDetector(RefactoringDetector):return []impact_lookup = self._impact_for_dry_violation(ctx)+ spans_cache: dict[str, list[tuple[int, int]]] = {}out: list[RefactoringSuggestion] = []for block in blocks:- suggestion = self._build_suggestion(ctx, block, impact_lookup)+ suggestion = self._build_suggestion(ctx, block, impact_lookup, spans_cache)if suggestion is not None:out.append(suggestion)@@ -324,6 +426,7 @@ class ExtractHelperDetector(RefactoringDetector):ctx: RefactoringContext,block: _Block,impact_lookup: list[tuple[int, int, float]],+ spans_cache: dict[str, list[tuple[int, int]]],) -> RefactoringSuggestion | None:# Drop test-file occurrences — duplication among fixtures is noise —# then coalesce the overlapping windows the clone detector emits for one@@ -334,7 +437,11 @@ class ExtractHelperDetector(RefactoringDetector):kept = [o for o in block.occurrences if not _is_skippable_occurrence(o[0], ctx.language)]- occurrences = _merge_ranges_per_file(kept)+ occurrences = [+ o+ for o in _merge_ranges_per_file(kept)+ if _within_one_declaration(o, ctx.graph, spans_cache)+ ]if len(occurrences) < 2:return None@@ -543,33 +650,29 @@ def _merge_ranges_per_file(return sorted(out)-def _suggested_name(suggested_site: dict[str, str | None]) -> str:- """A deterministic starting name for the extracted helper.-- Precision-first: without semantics we cannot name the block for what it- *does*, so we anchor the name to where the helper will live (the shared- directory leaf) and suffix ``_helper``. It is an editable starting point- (the UI frames it that way), not a claim about behaviour, so it stays- deterministic and never guesses intent. Falls back to ``shared_helper``- when the site has no usable label.+def _suggested_name(suggested_site: dict[str, str | None]) -> str | None:+ """Always ``None``: no fact this detector holds names the block.- Reads ``directory`` only. Plans stored before that key became the sole- namespace still carry a ``module`` community label, and it is precisely the- one that produced names like ``repowise_helper`` -- the repo naming its own- helper -- so it is not consulted as a fallback. ``directory`` was correct on- those rows too, which is why dropping the label needs no migration.+ The name used to be the shared directory's leaf plus ``_helper``, which+ says where the helper would live and nothing about what it does, and+ collides by construction -- six plans on this repo's index were all+ ``persistence_helper``. Naming the block needs its semantics, which is an+ opt-in LLM pass, not an index-time guess. Kept as a function, taking the+ site it used to read, so the one call site stays a named decision rather+ than a bare ``None`` literal in the plan dict."""- label = suggested_site.get("directory") or ""- leaf = label.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]- slug = identifier_slug(leaf)- if not slug:- return "shared_helper"- return slug if slug.endswith("helper") else f"{slug}_helper"+ return Nonedef _common_directory(paths: list[str]) -> str | None:- """Longest shared directory prefix of *paths* (POSIX), or ``None`` when- they share no directory. Component-wise, never mid-segment."""+ """The directory every occurrence shares *and* at least one lives in.++ A shared prefix alone is not a site: occurrences in ``packages/core/...``+ and ``packages/ui/...`` share ``packages``, a container holding no module,+ and proposing a helper there names a place nothing could go. Requiring one+ occurrence directly in the directory keeps the honest answer (they really+ are siblings) and returns ``None`` for the rest.+ """seg_lists = [p.replace("\\", "/").split("/")[:-1] for p in paths]if not seg_lists or any(not segs for segs in seg_lists):return None@@ -579,4 +682,7 @@ def _common_directory(paths: list[str]) -> str | None:common.append(parts[0])else:break- return "/".join(common) or None+ shared = "/".join(common)+ if not shared or not any(len(segs) == len(common) for segs in seg_lists):+ return None+ return shareddiff --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 fb4cad67b..c21e3dc48 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@@ -16,12 +16,11 @@ no suggestion.Plan shape (open dict, no migration):- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],- "returns": [str, ...], "suggested_name": str}`` -- the lines to lift, the- inferred signature, and a deterministic starting name (see- ``_suggested_name``). Always a string: the field used to be a hardcoded- ``None`` here while Extract Helper computed one, so its meaning depended on- which detector wrote the plan and every surface fell through to a generic- "helper".+ "returns": [str, ...], "suggested_name": str | None}`` -- the lines to lift,+ the inferred signature, and a deterministic starting name (see+ ``_suggested_name``). ``None`` when the span has no single informative OUT+ value: a name derived from the enclosing function described the context+ rather than the span, and collided with every sibling plan in the file.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size andcomplexity the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a new@@ -46,6 +45,12 @@ from .registry import RefactoringDetector, effort_bucket, registerif TYPE_CHECKING:from ..dataflow import Extraction, FunctionAnalysis+# OUT values whose name describes the variable's role, not the block's+# product: ``compute_result`` names nothing the reader did not know.+_UNINFORMATIVE_OUT = frozenset(+ {"out", "result", "results", "value", "values", "ret", "tmp", "temp", "data", "item"}+)+# The function-level structural biomarkers this detector answers. A function is# only offered an extraction when one of these flagged it, so the suggestion# list never exceeds (and stays consistent with) what health surfaces.@@ -125,7 +130,7 @@ class ExtractMethodDetector(RefactoringDetector):return best_impact, best_source@staticmethod- def _suggested_name(analysis: FunctionAnalysis, extraction: Extraction) -> str:+ def _suggested_name(analysis: FunctionAnalysis, extraction: Extraction) -> str | None:"""A deterministic starting name for the lifted helper.Same posture as Extract Helper (see ``naming``): anchor the name to@@ -150,10 +155,9 @@ class ExtractMethodDetector(RefactoringDetector):"""if len(extraction.returns) == 1:slug = identifier_slug(extraction.returns[0])- if slug:+ if slug and slug not in _UNINFORMATIVE_OUT:return f"compute_{slug}"- slug = identifier_slug(analysis.name)- return f"{slug}_helper" if slug else "extracted_helper"+ return None@staticmethoddef _confidence(extraction: Extraction) -> str:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.pyindex 13cdd64f2..191bdc1c3 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py@@ -359,11 +359,11 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {"Refactoring: EXTRACT METHOD. The target is one long function; the plan's ""'span' gives the line range to lift into a new helper method in the same ""scope. Move exactly those lines into the helper and name it: the plan's "- "'suggested_name' is a deterministic starting point, derived from the "- "slice's output value when it has exactly one and otherwise from the "- "enclosing function, so keep it unless the code clearly warrants a better "+ "'suggested_name' is a deterministic starting point derived from the "+ "slice's single output value, so keep it unless the code clearly warrants a better ""name -- and rename it if it collides with something already in the file, "- "which it can. Pass the plan's 'params' as its arguments "+ "which it can. When 'suggested_name' is null no name was anchored in the plan, "+ "so choose one that describes what the lifted code computes. Pass the plan's 'params' as its arguments ""and return the plan's 'returns' value(s), and replace the original lines ""with a call to it. Preserve behaviour exactly; change nothing outside the ""span and the single call site."@@ -372,6 +372,8 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {"Refactoring: SPLIT FILE. The module is too large and partitions into ""the cohesive groups in the plan. Create one new file per group at its ""'suggested_file' path, containing exactly that group's symbols, and "+ "when a group's 'suggested_file' is null pick a filename that describes "+ "its symbols, in the same directory as the original, and ""remove them from the original. Keep the residual 'core' symbols in the ""original file. When 'shim_required' is true, leave a back-compat ""re-export shim in the original path (import and re-export the moved "diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex d3dc57602..da90817df 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -25,7 +25,7 @@ For Extract Helper:"line_end": int}, ...], "suggested_site": {"directory": str | None},"duplicated_lines": int, "snippet": str | None,"snippet_start_line": int | None, "snippet_truncated": bool,- "suggested_name": str}`` lists every site of the duplicated block,+ "suggested_name": None}`` lists every site of the duplicated block,where the shared helper should live, and the block itself: the anchor site'ssourcetext (identical across sites by definition, so stored once and capped at@@ -46,10 +46,10 @@ For Extract Helper:For Extract Method:- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],- "returns": [str, ...], "suggested_name": str}`` — the lines to lift, the- inferred signature, and a deterministic starting name (from the slice's single- OUT value, else the enclosing function). Always a string; it is an editable- starting point and is not unique within a file.+ "returns": [str, ...], "suggested_name": str | None}`` — the lines to lift,+ the inferred signature, and a deterministic starting name (from the slice's+ single informative OUT value, else absent). It is an editable starting point+ and is not unique within a file.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` — the size andcomplexity the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` — the one type whose blast radius is@@ -81,7 +81,7 @@ For Break Cycle:For Split File:- ``plan`` = ``{"groups": [{"name": str | None, "symbols": [str, ...],- "suggested_file": str}], "residual": {"symbols": [...]} | None,+ "suggested_file": str | None}], "residual": {"symbols": [...]} | None,"shim_required": bool}`` — the cohesive groups the file should split into(each with a suggested filename), the shared-utility ``core`` left behind,and whether a back-compat re-export shim is needed (false for same-packagediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex be319f286..7338ddbe3 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -215,9 +215,10 @@ def detector_native_benefit(suggestion: RefactoringSuggestion) -> float:benefit = _DETECTOR_BENEFIT.get(suggestion.refactoring_type)if benefit is not None:return benefit(suggestion.evidence or {})- # A detector that emitted a concrete graph-native plan has a real but- # deliberately small gain even when it is not a defect-health deduction.- return 1.0 if suggestion.refactoring_type else 0.0+ # No health deduction and no detector-native measure: there is no+ # evidence of a gain, and a flat placeholder is what let zero-impact clones+ # in popular files lead the board. Report the absence.+ return 0.0@dataclass(frozen=True, slots=True)@@ -474,7 +475,8 @@ def _priority_components(entry_bonus = 0.5 if (suggestion.evidence or {}).get("reliable_entry_reachability") else 0.0leverage = 0.5 * math.log1p(weighted_deficit) + math.log1p(max(0, dependents)) + entry_bonussurface = max(blast_size(suggestion), max(0, len(affected_files(suggestion)) - 1))- cost = _EFFORT_COST.get(suggestion.effort_bucket, 3.0) + math.log1p(surface)+ # Blast radius is charged once, in ``risk``. Cost is the work itself.+ cost = _EFFORT_COST.get(suggestion.effort_bucket, 3.0)provenance = str((suggestion.evidence or {}).get("provenance") or "")weak_graph = 1.0 if provenance in _WEAK_PROVENANCE else 0.0validation_risk = {@@ -489,7 +491,11 @@ def _priority_components(+ weak_graph+ validation_risk)- priority = (1.0 + benefit) * (1.0 + leverage) / (1.0 + cost + risk)+ # Benefit multiplies rather than offsets: leverage (the host file's+ # deficit and dependents) scales a real gain, and scales nothing when+ # there is none. A plan with no evidence of benefit scores 0 and cannot+ # outrank one that recovers health, however popular its file.+ priority = benefit * (1.0 + leverage) / (1.0 + cost + risk)return (round(benefit, 4),round(leverage, 4),diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.pyindex 1a982c4af..ceb8d2c03 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py@@ -633,11 +633,15 @@ class SplitFileDetector(RefactoringDetector):groups: list[dict] = []self_segments = {seg.lower() for seg in ctx.file_path.replace("\\", "/").split("/")}self_segments.add(stem.lower())- for idx, members in enumerate(substantive, 1):+ for members in substantive:label = self._group_label(defined, foreign_of, members, self_segments)- file_stem = label or f"{stem}_part{idx}"- filename = self._unique_filename(file_stem, ext, used)- suggested = f"{directory}/{filename}" if directory else filename+ # A group whose symbols share no name token has no honest filename.+ # ``{stem}_part{idx}`` looked like one and named nothing, so the+ # field is absent instead and the surfaces prompt for a name.+ suggested = None+ if label:+ filename = self._unique_filename(label, ext, used)+ suggested = f"{directory}/{filename}" if directory else filenamegroups.append({"name": label or None,diff --git a/packages/ui/__tests__/refactoring/split-file-types.test.ts b/packages/ui/__tests__/refactoring/split-file-types.test.tsindex 134447319..015421cb6 100644--- a/packages/ui/__tests__/refactoring/split-file-types.test.ts+++ b/packages/ui/__tests__/refactoring/split-file-types.test.ts@@ -116,3 +116,23 @@ describe("split_file meta + self-check verdict", () => {expect(verdict?.detail).toContain("1 symbol duplicated");});});++describe("unnamed groups", () => {+ it("keeps an absent suggested_file absent rather than coercing it to a string", () => {+ const plan = {+ id: "r1",+ refactoring_type: "split_file",+ file_path: "pkg/big.py",+ target_symbol: "big.py",+ plan: {+ groups: [{ name: null, symbols: ["a", "b"], suggested_file: null }],+ residual: null,+ shim_required: true,+ },+ } as unknown as RefactoringPlan;++ const groups = splitGroups(plan);+ expect(groups).toHaveLength(1);+ expect(groups[0]).toMatchObject({ name: null, suggested_file: null });+ });+});diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.tsindex 7090bbeac..f1bab601a 100644--- a/packages/ui/src/refactoring/types.ts+++ b/packages/ui/src/refactoring/types.ts@@ -176,7 +176,7 @@ export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {export interface SplitGroup {name: string | null;symbols: string[];- suggested_file: string;+ suggested_file: string | null;}export function splitGroups(plan: RefactoringPlan): SplitGroup[] {@@ -187,7 +187,7 @@ export function splitGroups(plan: RefactoringPlan): SplitGroup[] {return {name: typeof rec.name === "string" ? rec.name : null,symbols: Array.isArray(rec.symbols) ? (rec.symbols as string[]) : [],- suggested_file: String(rec.suggested_file ?? ""),+ suggested_file: typeof rec.suggested_file === "string" ? rec.suggested_file : null,};});}diff --git a/pyproject.toml b/pyproject.tomlindex a73c51c92..dc57bb3a3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -192,7 +192,7 @@ line-length = 100# Language sample fixtures are analyzer *inputs*, not code we run. Several are# deliberately malformed (undefined names, unclosed file handles) because that is# exactly the finding the test asserts on. Linting them would fail forever.-extend-exclude = ["tests/fixtures/lang_samples"]+extend-exclude = ["tests/fixtures/lang_samples", "tests/fixtures/refactoring_corpus"][tool.ruff.lint]select = [diff --git a/tests/fixtures/refactoring_corpus/cases.py b/tests/fixtures/refactoring_corpus/cases.pynew file mode 100644index 000000000..f7f6e0bec--- /dev/null+++ b/tests/fixtures/refactoring_corpus/cases.py@@ -0,0 +1,195 @@+"""Extract Method soundness archetypes (Python).++``# unsound:`` marks a region the slicer must never offer; ``# sound:`` marks+one it must keep offering. The test reads the marker lines out of this file, so+the contract lives next to the code it describes.+"""+++def clean_extraction(results, threshold):+ total = 0+ count = 0+ for row in results:+ if row > threshold:+ total += row+ count += 1+ # sound: unconditional OUT, no enclosing loop+ average = 0.0+ if count:+ average = total / count+ else:+ average = 0.0+ label = "high" if average > threshold else "low"+ record(label)+ return average+++def changed_accumulator(entries, limit):+ """The conditionally-written loop accumulator, plus mutation of the list+ being iterated. This is the shape the repo's own top-ranked plan had."""+ changed = False+ for entry in list(entries):+ record(entry)+ # unsound: changed is written on one branch only+ if entry > limit:+ entries.remove(entry)+ record(entry)+ changed = True+ record(limit)+ record(entry)+ return changed+++def else_assigned_twin(entries, limit):+ """The same accumulator with an exhaustive else and no mutation."""+ changed = False+ for entry in entries:+ record(entry)+ # sound: every path writes changed+ if entry > limit:+ record(entry)+ changed = True+ else:+ record(limit)+ changed = False+ record(limit)+ record(entry)+ return changed+++def elif_else_chain(values, limit):+ label = ""+ for value in values:+ record(value)+ # sound: exhaustive if/elif/else+ if value > limit:+ record(value)+ label = "high"+ elif value == limit:+ record(limit)+ label = "equal"+ else:+ record(0)+ label = "low"+ record(limit)+ record(value)+ return label+++def if_without_else(values, limit):+ label = "unset"+ for value in values:+ record(value)+ # unsound: no else, so one path leaves label untouched+ if value > limit:+ record(value)+ record(limit)+ label = "high"+ record(limit)+ record(value)+ return label+++def loop_read_above_span(rows, limit):+ carry = 0+ for row in rows:+ record(carry)+ # unsound: carry is read above the span in the same loop+ if row > limit:+ record(row)+ carry = row + limit+ else:+ record(limit)+ carry = limit+ record(limit)+ record(row)+ return carry+++def loop_mutates_iterated(queue, limit):+ seen = 0+ for item in queue:+ record(item)+ # unsound: the span mutates the collection the loop iterates+ if item > limit:+ queue.pop()+ seen = seen + 1+ else:+ queue.append(item)+ seen = seen + 2+ record(limit)+ record(item)+ return seen+++def loop_local_span(rows, limit):+ out = []+ for row in rows:+ record(row)+ # sound: only loop-local state crosses the span boundary+ if row > limit:+ record(row)+ scaled = row * 2+ else:+ record(limit)+ scaled = row+ out.append(scaled)+ record(row)+ return out+++def loop_rebinds_iterable(entries, limit):+ """The iterable is reassigned on the loop body's first line, so a+ line-range test mistakes it for the loop's own binder."""+ for entry in entries:+ entries = list(entries)+ # unsound: the span mutates the collection the loop iterates+ if entry > limit:+ entries.remove(entry)+ record(entry)+ else:+ record(limit)+ record(entry)+ record(limit)+ record(entry)+ return entries+++def for_else_clause(rows, limit):+ """A ``for ... else`` clause runs once, not per iteration."""+ flag = ""+ total = 0+ for row in rows:+ total += row+ else:+ # sound: this clause is not loop-carried+ if total > limit:+ record(total)+ flag = "over"+ else:+ record(limit)+ flag = "under"+ record(limit)+ record(total)+ return flag+++def record(value):+ return value+++def try_except_assigned(rows, limit):+ """A write split across try/except cannot be proved exhaustive here."""+ rate = 0.0+ for row in rows:+ record(row)+ # unsound: neither arm is provably taken+ try:+ record(row)+ rate = row / limit+ except ZeroDivisionError:+ record(limit)+ rate = 0.0+ record(limit)+ record(row)+ return ratediff --git a/tests/fixtures/refactoring_corpus/cases.ts b/tests/fixtures/refactoring_corpus/cases.tsnew file mode 100644index 000000000..d0ad2e957--- /dev/null+++ b/tests/fixtures/refactoring_corpus/cases.ts@@ -0,0 +1,135 @@+// Extract Method soundness archetypes (TypeScript): the same gates on a+// second grammar. `// unsound:` marks a region the slicer must never offer,+// `// sound:` one it must keep offering.++function record(value: number): number {+ return value;+}++export function cleanExtraction(rows: number[], threshold: number): number {+ let total = 0;+ let count = 0;+ for (const row of rows) {+ total += row;+ count += 1;+ }+ // sound: unconditional OUT, no enclosing loop+ let average = 0;+ if (count) {+ average = total / count;+ } else {+ average = 0;+ }+ record(average);+ record(total);+ return average;+}++export function ifWithoutElse(values: number[], limit: number): string {+ let label = "unset";+ for (const value of values) {+ record(value);+ // unsound: no else, so one path leaves label untouched+ if (value > limit) {+ record(value);+ record(limit);+ label = "high";+ }+ record(limit);+ record(value);+ }+ return label;+}++export function elseAssignedTwin(values: number[], limit: number): string {+ let label = "unset";+ for (const value of values) {+ record(value);+ // sound: every path writes label+ if (value > limit) {+ record(value);+ label = "high";+ } else {+ record(limit);+ label = "low";+ }+ record(limit);+ record(value);+ }+ return label;+}++export function loopMutatesIterated(queue: number[], limit: number): number {+ let seen = 0;+ for (const item of queue) {+ record(item);+ // unsound: the span mutates the collection the loop iterates+ if (item > limit) {+ queue.pop();+ seen = seen + 1;+ } else {+ queue.push(item);+ seen = seen + 2;+ }+ record(limit);+ record(item);+ }+ return seen;+}++export function sameLineSibling(values: number[], limit: number): string {+ let label = "unset";+ for (const value of values) {+ record(value);+ // unsound: label is written on one branch only, and the sibling call on+ // that same line must not stand in as proof that it was+ if (value > limit) { label = "high"; } record(limit);+ record(+ value+ );+ record(+ limit+ );+ }+ return label;+}++export function elseIfChain(values: number[], limit: number): string {+ let label = "unset";+ for (const value of values) {+ record(value);+ // sound: exhaustive if / else if / else+ if (value > limit) {+ record(value);+ label = "high";+ } else if (value === limit) {+ record(limit);+ label = "equal";+ } else {+ record(0);+ label = "low";+ }+ record(limit);+ record(value);+ }+ return label;+}++// A member named like the iterated collection is not that collection.+export function memberNameCollision(pages: number[], limit: number): number {+ const bucket = { pages: [] as number[], total: 0 };+ for (const page of pages) {+ record(page);+ // sound: the receiver is bucket, not the iterated pages+ if (page > limit) {+ bucket.pages.push(page);+ bucket.total = bucket.total + 1;+ } else {+ bucket.pages.push(limit);+ bucket.total = bucket.total + 2;+ }+ record(limit);+ record(page);+ }+ return bucket.total;+}diff --git a/tests/fixtures/refactoring_corpus/golden_extractions.json b/tests/fixtures/refactoring_corpus/golden_extractions.jsonnew file mode 100644index 000000000..f3d91db4a--- /dev/null+++ b/tests/fixtures/refactoring_corpus/golden_extractions.json@@ -0,0 +1,1248 @@+{+ "python": {+ "changed_accumulator": [+ {+ "ccn_removed": 2,+ "end_line": 39,+ "params": [+ "entries",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 12,+ "start_line": 28+ },+ {+ "ccn_removed": 2,+ "end_line": 39,+ "params": [+ "entries",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 10,+ "start_line": 30+ }+ ],+ "clean_extraction": [+ {+ "ccn_removed": 4,+ "end_line": 23,+ "params": [+ "results",+ "threshold"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 14,+ "start_line": 10+ },+ {+ "ccn_removed": 4,+ "end_line": 23,+ "params": [+ "results",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 13,+ "start_line": 11+ },+ {+ "ccn_removed": 4,+ "end_line": 23,+ "params": [+ "count",+ "results",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 12,+ "start_line": 12+ },+ {+ "ccn_removed": 3,+ "end_line": 21,+ "params": [+ "results",+ "threshold"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 12,+ "start_line": 10+ },+ {+ "ccn_removed": 3,+ "end_line": 21,+ "params": [+ "results",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 11,+ "start_line": 11+ },+ {+ "ccn_removed": 3,+ "end_line": 21,+ "params": [+ "count",+ "results",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 10,+ "start_line": 12+ },+ {+ "ccn_removed": 2,+ "end_line": 23,+ "params": [+ "count",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 8,+ "start_line": 16+ },+ {+ "ccn_removed": 2,+ "end_line": 23,+ "params": [+ "count",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 7,+ "start_line": 17+ },+ {+ "ccn_removed": 2,+ "end_line": 23,+ "params": [+ "count",+ "threshold",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 6,+ "start_line": 18+ },+ {+ "ccn_removed": 1,+ "end_line": 21,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 6,+ "start_line": 16+ }+ ],+ "elif_else_chain": [+ {+ "ccn_removed": 3,+ "end_line": 75,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 15,+ "start_line": 61+ },+ {+ "ccn_removed": 2,+ "end_line": 75,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 13,+ "start_line": 63+ },+ {+ "ccn_removed": 2,+ "end_line": 74,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 63+ },+ {+ "ccn_removed": 2,+ "end_line": 75,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 64+ },+ {+ "ccn_removed": 2,+ "end_line": 73,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 63+ },+ {+ "ccn_removed": 2,+ "end_line": 74,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 64+ },+ {+ "ccn_removed": 2,+ "end_line": 75,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 65+ },+ {+ "ccn_removed": 2,+ "end_line": 73,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 10,+ "start_line": 64+ },+ {+ "ccn_removed": 2,+ "end_line": 74,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 10,+ "start_line": 65+ }+ ],+ "else_assigned_twin": [+ {+ "ccn_removed": 2,+ "end_line": 56,+ "params": [+ "entries",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 13,+ "start_line": 44+ },+ {+ "ccn_removed": 2,+ "end_line": 56,+ "params": [+ "entries",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 12,+ "start_line": 45+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 10,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 55,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 9,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 9,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 54,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 8,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 55,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 8,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 8,+ "start_line": 49+ },+ {+ "ccn_removed": 1,+ "end_line": 54,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 7,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 55,+ "params": [+ "entry",+ "limit"+ ],+ "returns": [+ "changed"+ ],+ "slice_nloc": 7,+ "start_line": 49+ }+ ],+ "for_else_clause": [+ {+ "ccn_removed": 2,+ "end_line": 173,+ "params": [+ "rows"+ ],+ "returns": [+ "flag"+ ],+ "slice_nloc": 15,+ "start_line": 159+ },+ {+ "ccn_removed": 2,+ "end_line": 173,+ "params": [+ "rows"+ ],+ "returns": [+ "flag"+ ],+ "slice_nloc": 14,+ "start_line": 160+ },+ {+ "ccn_removed": 2,+ "end_line": 173,+ "params": [+ "rows"+ ],+ "returns": [],+ "slice_nloc": 13,+ "start_line": 161+ },+ {+ "ccn_removed": 1,+ "end_line": 173,+ "params": [],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 166+ },+ {+ "ccn_removed": 1,+ "end_line": 172,+ "params": [],+ "returns": [],+ "slice_nloc": 7,+ "start_line": 166+ }+ ],+ "if_without_else": [+ {+ "ccn_removed": 2,+ "end_line": 89,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 10,+ "start_line": 80+ }+ ],+ "loop_local_span": [+ {+ "ccn_removed": 2,+ "end_line": 137,+ "params": [+ "limit",+ "rows"+ ],+ "returns": [+ "out"+ ],+ "slice_nloc": 12,+ "start_line": 126+ },+ {+ "ccn_removed": 1,+ "end_line": 137,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 10,+ "start_line": 128+ },+ {+ "ccn_removed": 1,+ "end_line": 136,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 128+ },+ {+ "ccn_removed": 1,+ "end_line": 137,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 129+ },+ {+ "ccn_removed": 1,+ "end_line": 135,+ "params": [+ "limit",+ "row"+ ],+ "returns": [+ "scaled"+ ],+ "slice_nloc": 8,+ "start_line": 128+ },+ {+ "ccn_removed": 1,+ "end_line": 136,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 129+ },+ {+ "ccn_removed": 1,+ "end_line": 137,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 130+ },+ {+ "ccn_removed": 1,+ "end_line": 135,+ "params": [+ "limit",+ "row"+ ],+ "returns": [+ "scaled"+ ],+ "slice_nloc": 7,+ "start_line": 129+ },+ {+ "ccn_removed": 1,+ "end_line": 136,+ "params": [+ "limit",+ "out",+ "row"+ ],+ "returns": [],+ "slice_nloc": 7,+ "start_line": 130+ }+ ],+ "loop_mutates_iterated": [+ {+ "ccn_removed": 2,+ "end_line": 121,+ "params": [+ "limit",+ "queue"+ ],+ "returns": [+ "seen"+ ],+ "slice_nloc": 12,+ "start_line": 110+ }+ ],+ "loop_read_above_span": [+ {+ "ccn_removed": 2,+ "end_line": 105,+ "params": [+ "limit",+ "rows"+ ],+ "returns": [+ "carry"+ ],+ "slice_nloc": 12,+ "start_line": 94+ },+ {+ "ccn_removed": 1,+ "end_line": 105,+ "params": [+ "carry",+ "limit",+ "row"+ ],+ "returns": [+ "carry"+ ],+ "slice_nloc": 10,+ "start_line": 96+ },+ {+ "ccn_removed": 1,+ "end_line": 104,+ "params": [+ "carry",+ "limit",+ "row"+ ],+ "returns": [+ "carry"+ ],+ "slice_nloc": 9,+ "start_line": 96+ },+ {+ "ccn_removed": 1,+ "end_line": 103,+ "params": [+ "carry",+ "limit",+ "row"+ ],+ "returns": [+ "carry"+ ],+ "slice_nloc": 8,+ "start_line": 96+ }+ ],+ "loop_rebinds_iterable": [],+ "record": [],+ "try_except_assigned": [+ {+ "ccn_removed": 2,+ "end_line": 194,+ "params": [+ "limit",+ "rows"+ ],+ "returns": [+ "rate"+ ],+ "slice_nloc": 13,+ "start_line": 182+ },+ {+ "ccn_removed": 2,+ "end_line": 194,+ "params": [+ "limit",+ "rows"+ ],+ "returns": [+ "rate"+ ],+ "slice_nloc": 12,+ "start_line": 183+ }+ ]+ },+ "typescript": {+ "cleanExtraction": [+ {+ "ccn_removed": 2,+ "end_line": 24,+ "params": [+ "rows"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 15,+ "start_line": 10+ },+ {+ "ccn_removed": 2,+ "end_line": 24,+ "params": [+ "rows",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 14,+ "start_line": 11+ },+ {+ "ccn_removed": 2,+ "end_line": 24,+ "params": [+ "count",+ "rows",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 13,+ "start_line": 12+ },+ {+ "ccn_removed": 1,+ "end_line": 24,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 9,+ "start_line": 16+ },+ {+ "ccn_removed": 1,+ "end_line": 23,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 8,+ "start_line": 16+ },+ {+ "ccn_removed": 1,+ "end_line": 24,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 8,+ "start_line": 17+ },+ {+ "ccn_removed": 1,+ "end_line": 22,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 7,+ "start_line": 16+ },+ {+ "ccn_removed": 1,+ "end_line": 23,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 7,+ "start_line": 17+ },+ {+ "ccn_removed": 1,+ "end_line": 24,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 7,+ "start_line": 18+ },+ {+ "ccn_removed": 1,+ "end_line": 22,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 6,+ "start_line": 17+ },+ {+ "ccn_removed": 1,+ "end_line": 23,+ "params": [+ "count",+ "total"+ ],+ "returns": [+ "average"+ ],+ "slice_nloc": 6,+ "start_line": 18+ }+ ],+ "elseAssignedTwin": [+ {+ "ccn_removed": 2,+ "end_line": 58,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 14,+ "start_line": 45+ },+ {+ "ccn_removed": 1,+ "end_line": 57,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 10,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 57,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 10,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 55,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 9,+ "start_line": 47+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 9,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 57,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 9,+ "start_line": 49+ },+ {+ "ccn_removed": 1,+ "end_line": 55,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 8,+ "start_line": 48+ },+ {+ "ccn_removed": 1,+ "end_line": 56,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 8,+ "start_line": 49+ }+ ],+ "elseIfChain": [+ {+ "ccn_removed": 3,+ "end_line": 114,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 17,+ "start_line": 98+ },+ {+ "ccn_removed": 2,+ "end_line": 113,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 14,+ "start_line": 100+ },+ {+ "ccn_removed": 2,+ "end_line": 112,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 13,+ "start_line": 100+ },+ {+ "ccn_removed": 2,+ "end_line": 113,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 13,+ "start_line": 101+ },+ {+ "ccn_removed": 2,+ "end_line": 111,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 100+ },+ {+ "ccn_removed": 2,+ "end_line": 112,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 101+ },+ {+ "ccn_removed": 2,+ "end_line": 113,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 102+ },+ {+ "ccn_removed": 2,+ "end_line": 111,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 101+ },+ {+ "ccn_removed": 2,+ "end_line": 112,+ "params": [+ "limit",+ "value"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 11,+ "start_line": 102+ }+ ],+ "ifWithoutElse": [+ {+ "ccn_removed": 2,+ "end_line": 40,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 12,+ "start_line": 29+ }+ ],+ "loopMutatesIterated": [+ {+ "ccn_removed": 2,+ "end_line": 76,+ "params": [+ "limit",+ "queue"+ ],+ "returns": [+ "seen"+ ],+ "slice_nloc": 14,+ "start_line": 63+ }+ ],+ "memberNameCollision": [+ {+ "ccn_removed": 2,+ "end_line": 133,+ "params": [+ "limit",+ "pages"+ ],+ "returns": [+ "bucket"+ ],+ "slice_nloc": 14,+ "start_line": 120+ },+ {+ "ccn_removed": 1,+ "end_line": 132,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 11,+ "start_line": 122+ },+ {+ "ccn_removed": 1,+ "end_line": 131,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 10,+ "start_line": 122+ },+ {+ "ccn_removed": 1,+ "end_line": 132,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 10,+ "start_line": 123+ },+ {+ "ccn_removed": 1,+ "end_line": 130,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 122+ },+ {+ "ccn_removed": 1,+ "end_line": 131,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 123+ },+ {+ "ccn_removed": 1,+ "end_line": 132,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 124+ },+ {+ "ccn_removed": 1,+ "end_line": 130,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 123+ },+ {+ "ccn_removed": 1,+ "end_line": 131,+ "params": [+ "bucket",+ "limit",+ "page"+ ],+ "returns": [],+ "slice_nloc": 8,+ "start_line": 124+ }+ ],+ "record": [],+ "sameLineSibling": [+ {+ "ccn_removed": 2,+ "end_line": 93,+ "params": [+ "limit",+ "values"+ ],+ "returns": [+ "label"+ ],+ "slice_nloc": 13,+ "start_line": 81+ }+ ]+ }+}diff --git a/tests/unit/health/refactoring_corpus_fixture.py b/tests/unit/health/refactoring_corpus_fixture.pynew file mode 100644index 000000000..a366334ef--- /dev/null+++ b/tests/unit/health/refactoring_corpus_fixture.py@@ -0,0 +1,90 @@+"""Loader for the checked-in Extract Method soundness corpus.++The corpus lives in ``tests/fixtures/refactoring_corpus``: archetype sources+plus one golden of the spans the slicer offers for each. A characterization run+needs no repository download, no index, and no network.++Each archetype marks its regions with a ``unsound:`` / ``sound:`` comment on+the line above the region's first statement, so the contract is readable in the+source rather than restated as line numbers in a test.++Regenerate the golden with ``REPOWISE_REWRITE_REFACTORING_GOLDEN=1``; never+hand-edit it.+"""++from __future__ import annotations++import json+import os+import re+from pathlib import Path+from typing import Any++CORPUS_DIR = Path(__file__).resolve().parents[2] / "fixtures" / "refactoring_corpus"+REWRITE_ENV = "REPOWISE_REWRITE_REFACTORING_GOLDEN"++# One source file per grammar. A language whose dataflow dialect is missing on+# the running interpreter is skipped by the test, not counted as clean.+CASE_FILES: tuple[tuple[str, str], ...] = (("python", "cases.py"), ("typescript", "cases.ts"))++_MARKER = re.compile(r"^\s*(?://|#)\s*(sound|unsound):")+++def rewrite_requested() -> bool:+ return os.environ.get(REWRITE_ENV, "") not in {"", "0", "false", "False"}+++def source_for(filename: str) -> bytes:+ return (CORPUS_DIR / filename).read_bytes()+++def marked_lines(filename: str, kind: str) -> list[int]:+ """1-indexed lines of the statements a ``kind:`` comment marks."""+ text = (CORPUS_DIR / filename).read_text(encoding="utf-8").splitlines()+ return [+ index + 2+ for index, line in enumerate(text)+ if (match := _MARKER.match(line)) and match.group(1) == kind+ ]+++def extractions_for(language: str, filename: str) -> dict[str, list[dict[str, Any]]]:+ """Every span the slicer offers, per function, for one corpus file.++ Keyed by function name so a golden diff names the archetype that moved.+ """+ from repowise.core.analysis.health.complexity.languages import get_language_map+ from repowise.core.analysis.health.dataflow.analyze import analyze_file+ from repowise.core.analysis.health.dataflow.slice import find_extractions++ lmap = get_language_map(language)+ result = analyze_file(filename, language, source_for(filename), flagged_only=False)+ out: dict[str, list[dict[str, Any]]] = {}+ for analysis in result.functions:+ out[analysis.name] = [+ {+ "start_line": item.start_line,+ "end_line": item.end_line,+ "params": list(item.params),+ "returns": list(item.returns),+ "slice_nloc": item.slice_nloc,+ "ccn_removed": item.ccn_removed,+ }+ for item in find_extractions(analysis, lmap)+ ]+ return out+++def offered_start_lines(language: str, filename: str) -> set[int]:+ spans = extractions_for(language, filename)+ return {item["start_line"] for rows in spans.values() for item in rows}+++def load_golden(name: str) -> Any:+ return json.loads((CORPUS_DIR / name).read_text(encoding="utf-8"))+++def write_golden(name: str, payload: Any) -> None:+ with (CORPUS_DIR / name).open("w", encoding="utf-8", newline="\n") as handle:+ json.dump(payload, handle, indent=2, sort_keys=True)+ handle.write("\n")diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.pyindex ccda6c748..9b9685d2a 100644--- a/tests/unit/health/test_recommendations.py+++ b/tests/unit/health/test_recommendations.py@@ -14,6 +14,7 @@ from repowise.core.analysis.health.refactoring.recommendations import (apply_view,build_recommendations,build_validation_plan,+ detector_native_benefit,hydrate_recommendations,rehydrate_suggestion,)@@ -341,3 +342,42 @@ def test_an_untruncated_test_list_keeps_the_precise_command() -> None:plan = build_validation_plan(_multi_site_plan(), {}, {"svc/orders.py": reached}, test_limit=12)assert plan.truncated is Falseassert plan.commands == ["pytest tests/test_orders.py::test_a tests/test_orders.py::test_b"]+++# ---- R1 ranking contract -------------------------------------------------+++def test_blast_radius_is_charged_once() -> None:+ narrow, wide = build_recommendations([_plan("narrow", blast=1), _plan("wide", blast=30)])+ by_target = {item.suggestion.target_symbol: item for item in (narrow, wide)}+ # Surface moves risk and only risk; effort alone sets cost.+ assert by_target["wide"].cost == by_target["narrow"].cost+ assert by_target["wide"].risk > by_target["narrow"].risk+++def test_zero_benefit_plan_cannot_outrank_a_health_recovering_one() -> None:+ # The zero-impact clone sits in the far more popular, far sicker file.+ clone = _plan("clone", rtype="extract_helper", file_path="src/hot.py", impact=0.0)+ real = _plan("real", rtype="extract_method", file_path="src/cold.py", impact=1.5)+ items = build_recommendations(+ [clone, real],+ metric_by_path={+ "src/hot.py": SimpleNamespace(nloc=4000, score=0.0),+ "src/cold.py": SimpleNamespace(nloc=40, score=9.0),+ },+ centrality={"src/hot.py": 300.0, "src/cold.py": 0.0},+ )+ by_target = {item.suggestion.target_symbol: item for item in items}+ assert by_target["clone"].benefit == 0.0+ assert by_target["clone"].rank_score == 0.0+ assert by_target["real"].rank_score > by_target["clone"].rank_score+ assert [item.suggestion.target_symbol for item in items] == ["real", "clone"]+++def test_performance_fix_benefit_stays_detector_native() -> None:+ evidence = {"rank_factors": {"loop_depth": 2.0, "affected_call_sites": 40.0}}+ plan = _plan("perf", rtype="performance_fix", impact=0.0, evidence=evidence)+ (item,) = build_recommendations([plan])+ native = detector_native_benefit(rehydrate_suggestion(plan))+ assert item.benefit == round(native, 4)+ assert item.benefit > 0.0diff --git a/tests/unit/health/test_refactoring_corpus_golden.py b/tests/unit/health/test_refactoring_corpus_golden.pynew file mode 100644index 000000000..4191328b1--- /dev/null+++ b/tests/unit/health/test_refactoring_corpus_golden.py@@ -0,0 +1,60 @@+"""Characterization of the Extract Method slicer over the archetype corpus.++The golden pins every span the slicer offers per archetype, so a gate change+has to explain each membership delta. The two marker tests state the soundness+contract the golden is only evidence for: a region a corpus source marks+``unsound:`` may never be offered, and one marked ``sound:`` must stay offered.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.dataflow.dialects import get_defuse_dialect++from .refactoring_corpus_fixture import (+ CASE_FILES,+ extractions_for,+ load_golden,+ marked_lines,+ offered_start_lines,+ rewrite_requested,+ write_golden,+)++GOLDEN = "golden_extractions.json"+++def _served() -> tuple[tuple[str, str], ...]:+ return tuple((lang, name) for lang, name in CASE_FILES if get_defuse_dialect(lang) is not None)+++def test_corpus_extractions_match_the_golden() -> None:+ served = _served()+ if not served:+ pytest.skip("no corpus language has a dataflow dialect here")+ payload = {language: extractions_for(language, name) for language, name in served}+ if rewrite_requested():+ write_golden(GOLDEN, payload)+ pytest.skip("golden rewritten")+ expected = load_golden(GOLDEN)+ assert payload == {key: value for key, value in expected.items() if key in payload}++[email protected](("language", "filename"), CASE_FILES)+def test_unsound_regions_are_never_offered(language: str, filename: str) -> None:+ if get_defuse_dialect(language) is None:+ pytest.skip(f"no dataflow dialect for {language} here")+ marked = marked_lines(filename, "unsound")+ assert marked, "corpus lost its unsound markers"+ assert not (set(marked) & offered_start_lines(language, filename))++[email protected](("language", "filename"), CASE_FILES)+def test_sound_regions_are_still_offered(language: str, filename: str) -> None:+ if get_defuse_dialect(language) is None:+ pytest.skip(f"no dataflow dialect for {language} here")+ marked = marked_lines(filename, "sound")+ assert marked, "corpus lost its sound markers"+ offered = offered_start_lines(language, filename)+ assert set(marked) <= offered, f"gate suppressed sound regions {sorted(set(marked) - offered)}"diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.pyindex 4112e5e7c..dc794d287 100644--- a/tests/unit/health/test_refactoring_extract_helper.py+++ b/tests/unit/health/test_refactoring_extract_helper.py@@ -20,6 +20,7 @@ from repowise.core.analysis.health.refactoring import (from repowise.core.analysis.health.refactoring.extract_helper import (_MAX_SNIPPET_LINES,_common_directory,+ _is_declaration_only,_merge_ranges_per_file,_suggested_name,)@@ -354,10 +355,13 @@ def _site_for(community_label_map: dict[str, str] | None) -> dict:return s.plan-def test_suggested_site_is_the_shared_directory_only():+def test_a_container_directory_is_not_a_site():+ """``pkg`` holds no occurrence, only other packages: naming it as the+ helper's home names a place nothing can go. This is the small-scale twin+ of ``suggested_site: "packages"`` on the real index."""plan = _site_for(None)- assert plan["suggested_site"] == {"directory": "pkg"}- assert plan["suggested_name"] == "pkg_helper"+ assert plan["suggested_site"] == {"directory": None}+ assert plan["suggested_name"] is Nonedef test_suggested_site_ignores_a_hostile_community_label():@@ -374,7 +378,7 @@ def test_suggested_site_ignores_a_hostile_community_label():hostile = {"pkg/api/a.py": "ui", "pkg/core/b.py": "ui"}assert _site_for(hostile) == _site_for(None)assert "module" not in _site_for(hostile)["suggested_site"]- assert _site_for(hostile)["suggested_name"] == "pkg_helper"+ assert _site_for(hostile)["suggested_name"] is Nonedef test_suggested_site_prefers_the_deepest_shared_directory():@@ -389,7 +393,10 @@ def test_suggested_site_prefers_the_deepest_shared_directory():def test_common_directory_helper():assert _common_directory(["a/b/x.py", "a/b/y.py"]) == "a/b"- assert _common_directory(["a/b/x.py", "a/c/y.py"]) == "a"+ # Shared prefix only: no occurrence lives directly in "a".+ assert _common_directory(["a/b/x.py", "a/c/y.py"]) is None+ # One does, so the directory is a real home for the helper.+ assert _common_directory(["a/x.py", "a/c/y.py"]) == "a"assert _common_directory(["a/x.py", "b/y.py"]) is Noneassert _common_directory(["x.py", "a/y.py"]) is None@@ -467,20 +474,16 @@ def test_suggested_name_from_directory():for s in detect_refactorings(_ctx("pkg/sub/a.py", [pair]))if s.refactoring_type == "extract_helper")- # directory site "pkg/sub" -> leaf "sub"- assert s.plan["suggested_name"] == "sub_helper"+ assert s.plan["suggested_name"] is None-def test_suggested_name_helper_unit():- assert _suggested_name({"directory": "api"}) == "api_helper"- # path leaf, hyphens normalised- assert _suggested_name({"directory": "web/api-client"}) == "api_client_helper"- # leading digit made identifier-safe- assert _suggested_name({"directory": "3d"}) == "_3d_helper"- # already ends in helper -> no double suffix- assert _suggested_name({"directory": "render_helper"}) == "render_helper"- # no usable label -> stable fallback- assert _suggested_name({"directory": None}) == "shared_helper"+def test_suggested_name_is_absent_rather_than_invented():+ """Where a block lives says nothing about what it does, and every block+ under one directory got the same name -- six plans on this repo's index+ were all ``persistence_helper``. Absent is the honest answer."""+ assert _suggested_name({"directory": "api"}) is None+ assert _suggested_name({"directory": "web/api-client"}) is None+ assert _suggested_name({"directory": None}) is Nonedef test_suggested_name_ignores_a_legacy_community_label():@@ -488,9 +491,9 @@ def test_suggested_name_ignores_a_legacy_community_label():``module``. It is the key that produced names like ``repowise_helper`` --the repo naming its own helper -- so it must not be revived as a fallback;``directory`` was the correct value on those rows and is what wins."""- assert _suggested_name({"module": "core", "directory": "pkg/sub"}) == "sub_helper"+ assert _suggested_name({"module": "core", "directory": "pkg/sub"}) is None# Even with no directory at all, the label is not consulted.- assert _suggested_name({"module": "repowise", "directory": None}) == "shared_helper"+ assert _suggested_name({"module": "repowise", "directory": None}) is None# ---- determinism ---------------------------------------------------------@@ -679,3 +682,196 @@ def test_declaration_only_unit_cases():assert not _is_declaration_only([" continue", " continue"])assert not _is_declaration_only([" break", " break"])assert not _is_declaration_only([" defer f.Close()", " defer g.Close()"])+++# ---- symbol-boundary gating ----------------------------------------------+++def _graph_with_symbols(spans: dict[str, list[tuple[str, int, int]]]):+ """A minimal repo graph: files defining symbols with declaration spans."""+ import networkx as nx++ graph = nx.DiGraph()+ for file_path, symbols in spans.items():+ graph.add_node(file_path, node_type="file")+ for name, start, end in symbols:+ sid = f"{file_path}::{name}"+ graph.add_node(+ sid,+ node_type="symbol",+ kind="class",+ name=name,+ file_path=file_path,+ start_line=start,+ end_line=end,+ )+ graph.add_edge(file_path, sid, edge_type="defines")+ return graph+++def _ctx_with_graph(file_path, clones, graph, source_lines=None):+ return RefactoringContext(+ file_path=file_path,+ language="python",+ nloc=200,+ classes=[],+ findings=[],+ dependents_count=0,+ clones=clones,+ graph=graph,+ community_label_map={},+ source_lines=source_lines,+ )+++def _helper_plans(ctx):+ return [s for s in detect_refactorings(ctx) if s.refactoring_type == "extract_helper"]+++def test_clone_inside_one_declaration_still_emits():+ graph = _graph_with_symbols(+ {"pkg/a.py": [("Alpha", 1, 40)], "pkg/b.py": [("Beta", 30, 70)]}+ )+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)+ assert len(_helper_plans(_ctx_with_graph("pkg/a.py", [pair], graph))) == 1+++def test_clone_crossing_a_declaration_boundary_is_dropped():+ # The a.py occurrence ends inside the next class, exactly the shape the+ # repo's own top-ranked plan had over SQLAlchemy models.+ graph = _graph_with_symbols(+ {"pkg/a.py": [("Alpha", 1, 20), ("Beta", 21, 60)], "pkg/b.py": [("Gamma", 30, 70)]}+ )+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)+ assert _helper_plans(_ctx_with_graph("pkg/a.py", [pair], graph)) == []+++def test_clone_swallowing_whole_declarations_is_dropped():+ graph = _graph_with_symbols(+ {"pkg/a.py": [("Alpha", 12, 18)], "pkg/b.py": [("Gamma", 30, 70)]}+ )+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)+ assert _helper_plans(_ctx_with_graph("pkg/a.py", [pair], graph)) == []+++def test_gate_abstains_without_symbol_facts():+ # A language whose symbols the graph does not carry keeps its plans.+ graph = _graph_with_symbols({"pkg/b.py": [("Gamma", 30, 70)]})+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)+ assert len(_helper_plans(_ctx_with_graph("pkg/a.py", [pair], graph))) == 1+++# ---- ORM / dataclass boilerplate: the correct answer is no suggestion -----+++_ORM_COLUMNS = [+ " id: Mapped[str] = mapped_column(",+ " String(32), primary_key=True, default=new_uuid",+ " )",+ " created_at: Mapped[datetime] = mapped_column(",+ " DateTime, nullable=False, default=utcnow",+ " )",+ " updated_at: Mapped[datetime] = mapped_column(",+ " DateTime, nullable=False, default=utcnow",+ " )",+ " repository_id: Mapped[str] = mapped_column(",+ ' ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False',+ " )",+]++_DATACLASS_FIELDS = [+ " names: list[str] = field(",+ " default_factory=list",+ " )",+ " counts: dict[str, int] = field(",+ " default_factory=dict",+ " )",+ " label: str = field(",+ ' default=""',+ " )",+ " tags: set[str] = field(",+ " default_factory=set",+ " )",+]+++def _boilerplate_plans(block: list[str]) -> list:+ source = ["" for _ in range(9)] + block+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 9 + len(block), 40, 39 + len(block))+ return _helper_plans(+ _ctx_with_graph(+ "pkg/a.py",+ [pair],+ _graph_with_symbols({"pkg/a.py": [("Model", 1, 400)], "pkg/b.py": [("Other", 1, 400)]}),+ source_lines=source,+ )+ )+++def test_multiline_orm_columns_emit_no_plan():+ assert _boilerplate_plans(_ORM_COLUMNS) == []+++def test_multiline_dataclass_fields_emit_no_plan():+ assert _boilerplate_plans(_DATACLASS_FIELDS) == []+++_TABLE_BODY = [+ ' __tablename__ = "wiki_symbols"',+ "",+ " id: Mapped[str] = mapped_column(String(32), primary_key=True)",+ " repository_id: Mapped[str] = mapped_column(",+ ' String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False',+ " )",+ " file_path: Mapped[str] = mapped_column(Text, nullable=False)",+ "",+ " __table_args__ = (",+ ' UniqueConstraint("repository_id", "file_path", name="uq_wiki_symbol"),',+ ' Index("ix_wiki_symbols_repo", "repository_id"),',+ " )",+]+++def test_declarative_table_body_emits_no_plan():+ assert _boilerplate_plans(_TABLE_BODY) == []+++# ---- logical-line joining must not swallow real behaviour ----------------+++def test_brace_language_bodies_are_not_declarations():+ """``{`` opens a body, not a continuation. Joining on it welded a whole+ function body into one line that then read as a bare signature."""+ go_body = ["func setup() {", " x := compute(a, b)", " cache.Store(x)", "}"]+ ts_body = ["function setup() {", " const x = compute(a, b);", " cache.store(x);", "}"]+ assert not _is_declaration_only(go_body)+ assert not _is_declaration_only(ts_body)+++def test_a_bracket_inside_a_string_does_not_absorb_the_next_statement():+ block = [+ "handler: Any = mapped_column(",+ ' String(32), doc="see note (ref"',+ ")",+ "do_side_effect(handler)",+ ]+ assert not _is_declaration_only(block)+++def test_a_one_line_body_is_not_a_signature():+ block = ["def compute(a, b): total = a + b; log(total)", "def other(c): v = c * 2; log(v)"]+ assert not _is_declaration_only(block)+++def test_a_signature_joined_back_whole_is_still_a_declaration():+ block = [+ "def update_command(",+ " path: str | None,",+ " dry_run: bool,",+ ") -> None:",+ "def run_update(",+ " path: str | None,",+ " dry_run: bool,",+ ") -> None:",+ ]+ assert _is_declaration_only(block)diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex 86d537851..b17ee46cc 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -154,6 +154,8 @@ def _find_extractions_reference(analysis, lmap):Extraction,_all_blocks,_infer_in_out,+ _loop_carry_free,+ _outs_definitely_assigned,_sorted,_span_metrics,_unwrap_container,@@ -185,7 +187,7 @@ def _find_extractions_reference(analysis, lmap):out = []evaluated = 0- for block in _all_blocks(fn_node, lmap.block_kinds, scope_kinds):+ for block, loop in _all_blocks(fn_node, lmap.block_kinds, scope_kinds, lmap.loop_kinds):stmts = block.named_childrenn = len(stmts)is_body = block.id == body_container.id@@ -217,6 +219,12 @@ def _find_extractions_reference(analysis, lmap):params, returns = _infer_in_out(def_lines, use_lines, s, e)if len(params) > _MAX_PARAMS or len(returns) > _MAX_RETURNS:continue+ if not _outs_definitely_assigned(span, returns, def_lines, lmap):+ continue+ if loop is not None and not _loop_carry_free(+ span, loop, s, e, def_lines, use_lines, lmap+ ):+ continueout.append(Extraction(start_line=s,@@ -386,14 +394,18 @@ def test_suggested_name_unit():assert name(_Analysis("process"), _Extraction(["average"])) == "compute_average"# Non-identifier characters normalised through the shared slug.assert name(_Analysis("p"), _Extraction(["total-count"])) == "compute_total_count"- # No single OUT -> fall back to the enclosing function, the only other- # anchor known for certain.- assert name(_Analysis("run_pipeline"), _Extraction([])) == "run_pipeline_helper"- assert name(_Analysis("run_pipeline"), _Extraction(["a", "b"])) == "run_pipeline_helper"+ # No single OUT -> no anchor, so no name. The enclosing function's name+ # described the span's context, never the span, and collided with every+ # sibling plan in the file.+ assert name(_Analysis("run_pipeline"), _Extraction([])) is None+ assert name(_Analysis("run_pipeline"), _Extraction(["a", "b"])) is None# A return name that slugs to nothing must not yield "compute_".- assert name(_Analysis("process"), _Extraction(["___"])) == "process_helper"- # Nothing usable at all -> a stable, still-valid identifier.- assert name(_Analysis(""), _Extraction([])) == "extracted_helper"+ assert name(_Analysis("process"), _Extraction(["___"])) is None+ # An OUT named for its role, not the product: "compute_result" names+ # nothing the reader did not already know.+ assert name(_Analysis("process"), _Extraction(["result"])) is None+ # Nothing usable at all -> no name at all.+ assert name(_Analysis("___"), _Extraction([])) is Nonedef test_detector_silent_without_matching_finding():