Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): write out an Extract Method helper's header and call (#3352)
Raghav Chamadiya3ed06a2d8708
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 956ab3d98..146b12324 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -220,6 +220,10 @@ Most plans answer a health finding, so per-path marker rules inobject's fields the span assigns directly, under `new_symbol`. A span that uses `this`outside a class, or writes fields of a Go value receiver, is a judgment call(`receiver_unbound`, `receiver_copy_written`).+- An Extract Method plan writes out the new helper's header and the line that+ replaces the span, in the file's language, with parameter types where the code+ declares them. Plan detail shows both with a copy button. Where the code names+ no helper or type, the text reads `<name>` or `<type>` for you to fill in.- Move Method never targets a class the method only instantiates, or an ancestor ofits own class.- Split File works on any language with call resolution and suggests a split onlydiff --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 d944700e1..11f143186 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@@ -66,7 +66,7 @@ def _render_refactoring_targets(ranked_plans = serialize_recommendations(build_recommendations(suggestions))[:limit]else:- ranked_plans = [_suggestion_to_dict(s) for s in suggestions][:limit]+ ranked_plans = [_list_row(_suggestion_to_dict(s)) for s in suggestions][:limit]# The composed unit. One opportunity per file, ranked, with its plans as# ordered steps - the same vocabulary the board, the drawer and the agent@@ -196,12 +196,21 @@ def _render_stored_refactoring_targets("opportunities_hidden": stored["hidden"],"targets": targets,"refactoring_opportunities": rows,- "refactoring_plans": plans,+ "refactoring_plans": [_list_row(plan) for plan in plans],},)return True+def _list_row(plan: dict) -> dict:+ """A plan as a list row: the rendered Extract Method texts stay on plan+ detail, as on every other list."""+ from repowise.core.analysis.health.refactoring.render import list_plan++ body = plan.get("plan")+ return {**plan, "plan": list_plan(body)} if isinstance(body, dict) else plan++def _rankable(findings: list, metrics: list) -> list:"""Findings on files that carry a score.diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py b/packages/core/src/repowise/core/analysis/health/dataflow/defuse.pyindex 2a716e8f4..4db5bfc39 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py@@ -40,6 +40,9 @@ class Definition:block_id: intindex: intline: int # 1-indexed+ #: Where on ``line`` the written name starts (0-indexed), so the write's+ #: node can be found again in the retained tree.+ column: int = 0#: Where on ``line`` a declared name starts to exist; see ``Occurrence``.declared_at: int | None = None#: The write declares the name (``Occurrence.declares``).@@ -101,6 +104,7 @@ def compute_def_use(block_id=block_id,index=counter,line=occ.line,+ column=occ.column,declared_at=occ.declared_at,declares=occ.declares,)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.pyindex 03f172234..829895444 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py@@ -476,6 +476,48 @@ class BaseDefUseDialect:"""The receiver *fn_node* declares itself. Default: None (unknown)."""return None+ def receiver_decl(self, fn_node: Node) -> str | None:+ """The text declaring *fn_node*'s receiver where a helper method must+ repeat it (a Go ``(s *S)``, a Rust ``&self``). Default: none."""+ return None++ # -- declared types ---------------------------------------------------------++ #: Nodes whose ``type`` field types the names they declare: a typed+ #: parameter, a typed local declaration.+ type_holder_kinds: frozenset[str] = frozenset()+ #: Declarators between a declared name and its holder (Java's+ #: ``variable_declarator``, C++'s ``init_declarator`` / ``pointer_declarator``).+ type_wrapper_kinds: frozenset[str] = frozenset()++ def declared_type(self, name: Node) -> str | None:+ """The type written where identifier *name* is declared, or None when+ the declaration writes none, or only asks for inference (``var``,+ ``auto``). Reads the retained tree around one node: no walk."""+ node, suffix = name.parent, ""+ while node is not None and node.type in self.type_wrapper_kinds:+ if node.child_by_field_name("dimensions") is not None:+ return None # Java ``int a[]``: the declarator changes the type+ suffix = self._declarator_token(node) + suffix+ node = node.parent+ if node is None or node.type not in self.type_holder_kinds:+ return None+ typ = node.child_by_field_name("type")+ if typ is None or typ.start_byte <= name.start_byte < typ.end_byte:+ return None+ text = " ".join(node_text(typ).lstrip(":").split())+ if not text or text in _INFERRED_TYPES:+ return None+ return self._type_prefix(node, typ) + text + suffix++ def _declarator_token(self, node: Node) -> str:+ """What declarator *node* adds to the type (C++ ``*`` / ``&``)."""+ return ""++ def _type_prefix(self, holder: Node, typ: Node) -> str:+ """Qualifiers written before the type (C++ ``const``)."""+ return ""+def _receiver(self, names: frozenset[str], **flags: bool) -> Receiver:return Receiver(names, self.member_access_kinds, self.receiver_write_kinds, **flags)@@ -505,6 +547,14 @@ class BaseDefUseDialect:uses.extend(echoes(inner_defs))+#: Type words that ask the compiler to infer the type: no type to repeat.+_INFERRED_TYPES = frozenset({"var", "auto", "_"})+++def node_text(node: Node) -> str:+ return (node.text or b"").decode("utf-8", "replace")++# Per closure-local name, the (start, end) points where that binding is in scope._Scopes = dict[str, list[tuple[tuple[int, int], tuple[int, int]]]]diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.pyindex 442ae0474..b23361487 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py@@ -38,7 +38,14 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse+from .base import (+ NO_RECEIVER,+ BaseDefUseDialect,+ Occurrence,+ Receiver,+ StatementDefUse,+ node_text,+)if TYPE_CHECKING:from tree_sitter import Node@@ -84,6 +91,10 @@ class CppDefUseDialect(BaseDefUseDialect):member_access_kinds = frozenset({_FIELD_EXPRESSION})receiver_write_kinds = _ASSIGN_KINDS | _UPDATE_KINDSkeyword_kinds = frozenset() # C++ has no keyword arguments.+ type_holder_kinds = frozenset(+ {"parameter_declaration", "optional_parameter_declaration", "declaration"}+ )+ type_wrapper_kinds = frozenset({"init_declarator", "pointer_declarator", "reference_declarator"})def _is_scope_boundary(self, node: Node) -> bool:return node.type in _SCOPE_BOUNDARIES@@ -130,6 +141,32 @@ class CppDefUseDialect(BaseDefUseDialect):out.append(self._occ(name_node))return tuple(out)+ def receiver_decl(self, fn_node: Node) -> str | None:+ """``const`` when the member function is (``int f() const``): a helper+ method it calls must be ``const`` too."""+ node = fn_node.child_by_field_name("declarator")+ while node is not None and node.type != "function_declarator":+ node = node.child_by_field_name("declarator")+ if node is None:+ return None+ quals = {node_text(c) for c in node.children if c.type == "type_qualifier"}+ return "const" if "const" in quals else None++ def _declarator_token(self, node: Node) -> str:+ """``*`` for a pointer declarator, ``&`` / ``&&`` for a reference."""+ if node.type == "init_declarator" or not node.children:+ return ""+ return node_text(node.children[0])++ def _type_prefix(self, holder: Node, typ: Node) -> str:+ """``const`` / ``volatile`` written before the type."""+ quals = [+ node_text(c)+ for c in holder.named_children+ if c.type == "type_qualifier" and c.end_byte <= typ.start_byte+ ]+ return "".join(q + " " for q in quals)+def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:"""``this`` for a member function defined in its class (a bare namecan also be a field); none for a ``static`` one or a free function.diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.pyindex ee2226adc..f224c526c 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py@@ -19,7 +19,14 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING-from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse+from .base import (+ NO_RECEIVER,+ BaseDefUseDialect,+ Occurrence,+ Receiver,+ StatementDefUse,+ node_text,+)if TYPE_CHECKING:from tree_sitter import Node@@ -46,6 +53,7 @@ class GoDefUseDialect(BaseDefUseDialect):language = "go"member_access_kinds = frozenset({"selector_expression"})receiver_write_kinds = _ASSIGN_KINDS | _INC_DEC_KINDS+ type_holder_kinds = frozenset({"parameter_declaration", "var_spec"})keyword_kinds = frozenset() # Go has no keyword arguments.def _is_scope_boundary(self, node: Node) -> bool:@@ -80,6 +88,11 @@ class GoDefUseDialect(BaseDefUseDialect):out.append(self._occ(child))return tuple(out)+ def receiver_decl(self, fn_node: Node) -> str | None:+ """The method's receiver list, ``(s *S)``, which a helper method repeats."""+ plist = fn_node.child_by_field_name("receiver")+ return node_text(plist) if plist is not None else None+def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:"""The method receiver's own name; a value receiver (``s T``, not``s *T``) is a copy. An unnamed receiver is unreachable from the body."""diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.pyindex 285388e5b..7f57e3cee 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py@@ -55,6 +55,10 @@ class JavaDefUseDialect(BaseDefUseDialect):language = "java"member_access_kinds = frozenset({"field_access"})receiver_write_kinds = _ASSIGN_KINDS | _UPDATE_KINDS+ type_holder_kinds = frozenset(+ {"formal_parameter", "local_variable_declaration", "enhanced_for_statement"}+ )+ type_wrapper_kinds = frozenset({"variable_declarator"})keyword_kinds = frozenset() # Java has no keyword arguments.def _is_scope_boundary(self, node: Node) -> bool:diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.pyindex 8222a4832..702dab908 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py@@ -46,6 +46,7 @@ class PythonDefUseDialect(BaseDefUseDialect):language = "python"member_access_kinds = frozenset({"attribute"})receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS+ type_holder_kinds = frozenset({"typed_parameter", "typed_default_parameter", "assignment"})keyword_kinds = frozenset({"keyword_argument"})# A nested ``def`` is visible in the enclosing scope from its statement on.diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.pyindex c0e10c59c..99dbaba11 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py@@ -39,6 +39,7 @@ from .base import (Receiver,StatementDefUse,echoes,+ node_text,)if TYPE_CHECKING:@@ -101,6 +102,7 @@ class RustDefUseDialect(BaseDefUseDialect):language = "rust"member_access_kinds = frozenset({"field_expression"})receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS+ type_holder_kinds = frozenset({"parameter", "let_declaration"})keyword_kinds = frozenset() # struct-literal field names are not reads.# ``self`` is its own node type in tree-sitter-rust, not an ``identifier``;# without it here every ``self.field`` read would drop its receiver (Go and@@ -150,6 +152,14 @@ class RustDefUseDialect(BaseDefUseDialect):self._targets(child.child_by_field_name("pattern"), out, sink)return tuple(out)+ def receiver_decl(self, fn_node: Node) -> str | None:+ """The ``self_parameter`` as written (``&self``, ``&mut self``, ``self``)."""+ params = fn_node.child_by_field_name("parameters")+ found = next(+ (c for c in params.named_children if c.type == "self_parameter"), None+ ) if params is not None else None+ return node_text(found) if found is not None else None+def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:"""``self`` when the signature takes it (``self_parameter``)."""params = fn_node.child_by_field_name("parameters")diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.pyindex 0720e4f68..18ea61079 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py@@ -68,6 +68,7 @@ class TsJsDefUseDialect(BaseDefUseDialect):language = "typescript"member_access_kinds = frozenset({"member_expression"})receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS | _UPDATE_KINDS+ type_holder_kinds = frozenset({"required_parameter", "optional_parameter", "variable_declarator"})keyword_kinds = frozenset() # object-property keys are not variable reads.# ``shorthand_property_identifier`` is an object-literal read (``{ days }``# reads the local ``days``). Its ``_pattern`` twin is the destructuringdiff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.pyindex a1e25235d..922c05b11 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py@@ -11,6 +11,8 @@ from __future__ import annotationsimport posixpath+from ..refactoring.render import brief+TITLE_MAX = 90#: What the finding says about the code, completing "<subject> ...". The@@ -338,15 +340,11 @@ def history_fact(marker: str, details: dict, function: str | None = None) -> strdef signature(name: str | None, params: list[str], returns: list[str], *, is_async: bool = False) -> str:- """``compute_x(a, b) -> c``; a long parameter list is cut with its count.- A span that awaits becomes ``async compute_x(...)``, awaited where it was."""- shown = ", ".join(params[:4]) + (f", +{len(params) - 4} more" if len(params) > 4 else "")- helper = "an async helper" if is_async else "a helper"- out = f"{name}({shown})" if name else helper + (f" taking ({shown})" if params else "")- out += f" -> {', '.join(returns[:3])}" if returns else ""- if not is_async:- return out- return f"{'async ' if name else ''}{out}, awaited at the call site"+ """``_load(path) -> config``, as the plan's renderer phrases it+ (``refactoring.render.brief``); a helper with no name reads ``<name>(...)``+ and asks the reader to name it."""+ out = brief(name, params, returns, is_async=is_async)+ return out if name else f"{out}; name it for what the lines do"def first_sentence(text: str) -> str: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 c14ebccf9..4dad5094a 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@@ -64,6 +64,16 @@ Plan shape (open dict, no migration):``needs_async`` stays for stored rows and their readers. ``plan.receiver_hazard`` is set only when thereceiver cannot be shared as it is (``_receiver_hazard``), which makes thestep a judgment call.+- ``new_symbol`` also carries ``params`` (``[{"name", "type", "mode": "in" |+ "inout"}]``, the receiver left out of a method's) and ``returns``+ (``[{"name", "type"}]``), each type read off the name's declaration (None+ without one), and ``signature_text``, the helper's header in the file's+ language; ``plan.call_site`` = ``{"replace_span": {"start", "end"},+ "new_text": str}`` is the statement replacing the span (``render``), and+ ``new_symbol.notes`` what they cannot say. Both texts are None when+ ``kind`` is; ``call_site`` also when an awaiting span sits in a host that+ is not async. A missing name reads ``<name>`` in them,+ and ``suggested_name`` is in the language's private form (Python ``_x``).- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size andcomplexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a new@@ -90,6 +100,7 @@ from ..dataflow import find_extractions, get_defuse_dialectfrom ..effort import effort_bucketfrom ..perf.dialects import PERF_DIALECTSfrom ..scoring import severity_deduction+from . import renderfrom .helper_naming import ScopeNames, helper_name, out_value_namefrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, register@@ -97,7 +108,7 @@ from .registry import RefactoringDetector, registerif TYPE_CHECKING:from ..complexity.languages import LanguageNodeMapfrom ..dataflow import Extraction, FunctionAnalysis- from ..dataflow.dialects.base import Receiver+ from ..dataflow.dialects.base import BaseDefUseDialect, Receiverfrom ..models import Severity# The function-level structural biomarkers this detector answers. A function is@@ -161,6 +172,23 @@ class ExtractMethodDetector(RefactoringDetector):if best is None:continueimpact, share, source = self._impact_for(analysis, best, matched)+ name = render.private_name(+ ctx.language,+ names.claim(+ analysis,+ helper_name(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),+ )out.append(RefactoringSuggestion(refactoring_type=self.name,@@ -172,14 +200,9 @@ class ExtractMethodDetector(RefactoringDetector):"span": {"start": best.start_line, "end": best.end_line},"params": list(best.params),"returns": list(best.returns),- "suggested_name": names.claim(- analysis,- helper_name(- analysis, best, lmap, ctx.language, names.imports(analysis.fn_node)- ),- ),- **_async_fields(analysis, best, lmap, ctx.language),- **_symbol_fields(best, receiver),+ "suggested_name": name,+ **async_fields,+ **symbol,},evidence={"slice_nloc": best.slice_nloc,@@ -309,6 +332,120 @@ def _symbol_fields(extraction: Extraction, receiver: Receiver | None) -> dict[streturn fields+def _render_fields(+ analysis: FunctionAnalysis,+ extraction: Extraction,+ dialect: BaseDefUseDialect | None,+ language: str | None,+ name: str | None,+ symbol: dict[str, Any],+ *,+ async_host: bool,+) -> dict[str, Any]:+ """*symbol* with ``new_symbol`` given its typed ``params`` / ``returns``,+ ``signature_text`` and any ``notes``, plus ``call_site`` (``render``).+ Types are read off the retained tree at each name's declaration, only for+ this plan's few names; the texts are None when the helper's form is+ unknown, and ``call_site`` also when the host cannot await the helper."""+ new_symbol = symbol["new_symbol"]+ types = _declared_types(analysis, extraction, dialect)+ # Only a Rust value moves when passed, so only Rust asks what is read later.+ after = _read_after(analysis, extraction) if language == "rust" else set()+ # A method reaches its instance through the receiver, not an argument.+ own = new_symbol["receiver"] if new_symbol["kind"] == "method" else None+ params = tuple(+ render.Slot(p, types.get(p), p in after) for p in extraction.params if p != own+ )+ returns = tuple(render.Slot(r, types.get(r)) for r in extraction.returns)+ declared, before, rebound = _out_binding(analysis, extraction)+ fn_node = analysis.fn_node+ texts = render.render(+ render.HelperShape(+ language=language or "",+ name=name,+ kind=new_symbol["kind"],+ is_async=extraction.needs_async,+ params=params,+ returns=returns,+ receiver=new_symbol["receiver"],+ receiver_decl=dialect.receiver_decl(fn_node) if dialect and fn_node else None,+ async_host=async_host,+ out_declared=declared,+ out_written_before=before,+ out_rebound=rebound,+ )+ )+ rendered = {+ **new_symbol,+ "params": render.symbol_params(params, returns),+ "returns": [{"name": r.name, "type": r.type} for r in returns],+ "signature_text": texts.signature if texts else None,+ }+ if texts and texts.notes:+ rendered["notes"] = list(texts.notes)+ span = {"start": extraction.start_line, "end": extraction.end_line}+ call = texts.call if texts else None+ return {+ **symbol,+ "new_symbol": rendered,+ "call_site": {"replace_span": span, "new_text": call} if call else None,+ }+++def _declared_types(+ analysis: FunctionAnalysis, extraction: Extraction, dialect: BaseDefUseDialect | None+) -> dict[str, str]:+ """Each IN / OUT name's declared type, from its latest typed write at or+ before the span's end (a parameter, a typed declaration). Definitions are+ numbered by CFG block, not source order, so they are sorted first."""+ fn_node = analysis.fn_node+ wanted = set(extraction.params) | set(extraction.returns)+ if dialect is None or fn_node is None or not wanted:+ return {}+ writes = sorted(+ (d for d in analysis.def_use.definitions if d.var in wanted and d.line <= extraction.end_line),+ key=lambda d: (d.line, d.column),+ reverse=True,+ )+ found: dict[str, str] = {}+ for d in writes:+ if d.var in found:+ continue+ raw = d.var.encode()+ row = d.line - 1+ # Tree points are byte columns.+ node = fn_node.descendant_for_point_range((row, d.column), (row, d.column + len(raw)))+ if node is not None and node.text == raw:+ typ = dialect.declared_type(node)+ if typ:+ found[d.var] = typ+ return found+++def _read_after(analysis: FunctionAnalysis, extraction: Extraction) -> set[str]:+ """The IN names the function reads after the span (a closure's read counts+ where the closure is written)."""+ wanted, e = set(extraction.params), extraction.end_line+ def_use = analysis.def_use+ uses = [u for bdu in def_use.blocks.values() for u in bdu.uses if not u.echo]+ return {u.name for u in (*uses, *def_use.captured.reads) if u.name in wanted and u.line > e}+++def _out_binding(+ analysis: FunctionAnalysis, extraction: Extraction+) -> tuple[bool, bool, bool]:+ """Whether the span's output is declared in it (the call must declare it:+ an in-span declaration, or no write before the span), whether it was+ written before the span, and whether it is written again after it."""+ if not extraction.returns:+ return False, False, False+ out, s, e = extraction.returns[0], extraction.start_line, extraction.end_line+ writes = [d for d in analysis.def_use.definitions if d.var == out]+ before = any(d.line < s for d in writes)+ declared = any(s <= d.line <= e and d.declares for d in writes) or not before+ return declared, before, any(d.line > e for d in writes)++def _receiver_hazard(receiver: Receiver | None, uses: bool | None, assigns: tuple[str, ...] | None) -> str | None: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 4db1fb54f..d83ac5576 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@@ -294,10 +294,14 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {"'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. 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. When the plan's 'needs_async' is true the span awaits: "+ "which it can. When 'suggested_name' is null no name was anchored in the plan "+ "and the texts below read '<name>': choose one that describes what the lifted "+ "code does. The plan's 'new_symbol.signature_text' is the helper's header and "+ "'call_site.new_text' the statement that replaces the span; use both, filling "+ "any '<name>' or '<type>' placeholder, and follow 'new_symbol.notes'. "+ "Without them (an older plan, or one whose helper form is unknown), pass the plan's 'params' "+ "as its arguments, return the plan's 'returns' value(s), and replace the "+ "original lines with a call to it. When the plan's 'needs_async' is true the span awaits: ""declare the helper async and await the call that replaces the lines. ""When the plan's 'new_symbol.kind' is 'method' the span uses its receiver ""('new_symbol.receiver'): make the helper a method of the same object and "diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex 837155c15..8ddd58cc0 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -52,7 +52,8 @@ For Extract Method:span; never one already taken in the helper's scope; else absent), andwhether the span awaits, so the helper is async and its call awaited. Anawaiting plan adds ``"async_host": bool``, False when the enclosing function- is not async.+ is not async. ``new_symbol`` and ``call_site`` carry the helper's typed+ parameters, its header and its call, written out (``extract_method``).- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` — the size andcomplexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` — the one type whose blast radius isdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex d65651fcd..e81f9eea3 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -42,6 +42,7 @@ from repowise.core.test_paths import is_test_support_path, names_test_for, pairefrom .annotations import PlanAnnotations, partner_rowsfrom .models import RefactoringSuggestion+from .render import list_planRecommendationView = Literal["canonical", "file_spread"]ValidationBasis = Literal["measured", "inferred", "mixed", "unknown"]@@ -1034,7 +1035,8 @@ class Recommendation:"target_symbol": suggestion.target_symbol,"line_start": suggestion.line_start,"line_end": suggestion.line_end,- "plan": suggestion.plan or {},+ # Rendered texts stay on detail (:meth:`detail_dict`).+ "plan": list_plan(suggestion.plan or {}),"evidence": suggestion.evidence or {},"impact_delta": round(float(suggestion.impact_delta or 0.0), 3),"effort_bucket": suggestion.effort_bucket,@@ -1053,10 +1055,12 @@ class Recommendation:}def detail_dict(self) -> dict[str, Any]:- """:meth:`as_dict` for one plan read alone: a step whose checks differ- from the plan's carries its ``verify``, and the plan carries its- ``governed_by``, ``risks`` and co-change partners."""+ """:meth:`as_dict` for one plan read alone: the whole stored plan,+ rendered texts included, a step whose checks differ from the plan's+ carrying its ``verify``, and the plan's ``governed_by``, ``risks`` and+ co-change partners."""payload = self.as_dict()+ payload["plan"] = self.suggestion.plan or {}steps = payload["plan"].get("steps")if isinstance(steps, list) and self.validation.step_verify:payload["plan"] = {diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/render.py b/packages/core/src/repowise/core/analysis/health/refactoring/render.pynew file mode 100644index 000000000..cce408481--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py@@ -0,0 +1,420 @@+"""The helper an Extract Method plan asks for, written out in the file's language.++A plan names the lines to lift, their inputs and output, whether the helper is+a method and whether it awaits. An agent applying it still had to turn that+into a header and a call. This module writes both, as text the agent copies:+Repowise never applies an edit, so they are spec, not a patch.++``signature_text`` is the helper's header (``async def _load(self, path: Path)+-> Config:``, ``private loadConfig(path: string): Config {``, ``func (s *S)+load(path string) Config {``); ``call_site.new_text`` is the one statement+that replaces the span (``config = await self._load(path)``,+``const config = this.loadConfig(path);``). Neither is indented: the+statement takes the replaced lines' indentation. ``notes`` say what the texts+cannot (a Rust value that may move, a coroutine's return type).++Per language: the private convention (Python's leading underscore, TS+``private``, Java ``private``, a C++ ``static`` free function; Go's lower-case+first letter and Rust's missing ``pub`` already hold), the async form+(``async`` + ``await``, Rust ``.await``, C++ ``co_await``), the receiver a+method keeps (a C++ ``const`` member stays ``const``), and how the call+declares an output first declared in the span (``const`` / ``let``, Go+``:=`` unless the name was written before, Rust ``let`` / ``let mut``, Java /+C++ the declared type, ``var`` / ``auto`` without one). A Rust value the host+still reads after the call is borrowed, not moved. A type the parse does not+name is left out where the language allows it (Python, TS / JS) and written+``<type>`` where it does not (Go, Java, Rust, C / C++); a missing name is+``<name>``. Both are placeholders the agent must replace.++Ceilings: one output at most, as the slicer never offers more+(``dataflow.slice._MAX_RETURNS``); C7's staged plans bring tuple returns. A+C++ method defined out of line (``A::f``) has an unknown receiver, so it gets+no texts and the header is never qualified.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal, NamedTuple, get_args++ParamMode = Literal["in", "inout"]+#: ``inout``: the helper takes the value and hands its new value back.+PARAM_MODES: tuple[str, ...] = get_args(ParamMode)++NAME_PLACEHOLDER = "<name>"+TYPE_PLACEHOLDER = "<type>"++_FAMILY: dict[str, str] = {+ "python": "python",+ "typescript": "ts",+ "tsx": "ts",+ "javascript": "js",+ "jsx": "js",+ "svelte": "js",+ "vue": "js",+ "go": "go",+ "java": "java",+ "rust": "rust",+ "cpp": "cpp",+ "c": "cpp",+}+#: Languages whose signatures need every type written.+_TYPED = frozenset({"go", "java", "rust", "cpp"})+#: Rust types that copy rather than move when passed by value.+_RUST_COPY = frozenset(+ {+ *(f"{s}{n}" for s in "iu" for n in ("8", "16", "32", "64", "128", "size")),+ "f32",+ "f64",+ "bool",+ "char",+ }+)+++@dataclass(frozen=True)+class Slot:+ """One parameter or output: its name, declared type (None: unknown), and+ whether the host reads it after the span (a Rust move would end that)."""++ name: str+ type: str | None = None+ read_after: bool = False+++@dataclass(frozen=True)+class HelperShape:+ """What the renderer needs to know about one helper.++ ``receiver`` is the name a method reaches its instance by (``self``,+ ``cls``, ``this``, a Go receiver) and ``receiver_decl`` the text a method+ repeats (Go ``(s *S)``, Rust ``&mut self``, C++ trailing ``const``).+ ``async_host`` False: the host is not declared async, so nothing there can+ await the helper. ``out_declared``: the output is first declared in the+ span, so the call declares it; ``out_written_before``: it was written+ before the span (Go's ``:=`` would then declare nothing new);+ ``out_rebound``: it is assigned again after the span.+ """++ language: str+ name: str | None+ kind: str | None+ is_async: bool+ params: tuple[Slot, ...] = ()+ returns: tuple[Slot, ...] = ()+ receiver: str | None = None+ receiver_decl: str | None = None+ async_host: bool = True+ out_declared: bool = False+ out_written_before: bool = False+ out_rebound: bool = False+++class Rendered(NamedTuple):+ signature: str+ call: str | None+ notes: tuple[str, ...]+++def private_name(language: str | None, name: str | None) -> str | None:+ """*name* in the language's private form: Python's leading underscore.+ Other languages mark privacy on the header, or already have it in the+ name's case (Go)."""+ if name and _FAMILY.get(language or "") == "python" and not name.startswith("_"):+ return "_" + name+ return name+++def symbol_params(params: tuple[Slot, ...], returns: tuple[Slot, ...]) -> list[dict]:+ """``new_symbol.params``: name, type, and ``inout`` for a value the helper+ also returns."""+ outs = {r.name for r in returns}+ return [+ {"name": p.name, "type": p.type, "mode": "inout" if p.name in outs else "in"}+ for p in params+ ]+++def render(shape: HelperShape) -> Rendered | None:+ """The header, the call (None when the host cannot await the helper) and+ notes, or None when the helper's form is not known: a language without a+ renderer, or ``kind`` None, where the span may reach its object by a name+ a function would not have, so a function header would be a confident+ wrong spec."""+ family = _FAMILY.get(shape.language)+ if family is None or shape.kind not in ("method", "function"):+ return None+ sig, call = _RENDERERS[family]+ notes = list(_notes(shape, family))+ if shape.is_async and not shape.async_host:+ notes.append(+ "The function holding these lines is not async, so the call cannot await "+ "the helper where it stands."+ )+ return Rendered(sig(shape), None, tuple(notes))+ return Rendered(sig(shape), call(shape), tuple(notes))+++def _notes(s: HelperShape, family: str) -> list[str]:+ out = []+ if family == "rust":+ unknown = [p.name for p in _rust_unsure(s)]+ if unknown:+ out.append(+ f"Pass {', '.join(unknown)} by reference (&) unless the type is Copy: "+ "the caller still reads it after the call."+ )+ if family == "cpp" and s.is_async:+ out.append("Give the helper the coroutine return type the caller co_awaits.")+ return out+++# -- shared pieces -----------------------------------------------------------+++def _name(shape: HelperShape) -> str:+ return shape.name or NAME_PLACEHOLDER+++def _type(slot: Slot, family: str) -> str | None:+ return slot.type or (TYPE_PLACEHOLDER if family in _TYPED else None)+++def _args(shape: HelperShape) -> str:+ return ", ".join(p.name for p in shape.params)+++def _out(shape: HelperShape) -> Slot | None:+ return shape.returns[0] if shape.returns else None+++def _method(shape: HelperShape) -> bool:+ return shape.kind == "method"+++# -- Python ------------------------------------------------------------------+++def _py_sig(s: HelperShape) -> str:+ params = [f"{p.name}: {p.type}" if p.type else p.name for p in s.params]+ if _method(s) and s.receiver:+ params.insert(0, s.receiver)+ out = _out(s)+ ret = f" -> {out.type}" if out and out.type else ""+ head = f"{'async ' if s.is_async else ''}def {_name(s)}({', '.join(params)}){ret}:"+ return ("@classmethod\n" + head) if _method(s) and s.receiver == "cls" else head+++def _py_call(s: HelperShape) -> str:+ target = f"{s.receiver}." if _method(s) and s.receiver else ""+ expr = f"{'await ' if s.is_async else ''}{target}{_name(s)}({_args(s)})"+ out = _out(s)+ return f"{out.name} = {expr}" if out else expr+++# -- TypeScript / JavaScript -------------------------------------------------+++def _ts_sig(s: HelperShape, typed: bool) -> str:+ params = ", ".join(f"{p.name}: {p.type}" if p.type else p.name for p in s.params)+ out = _out(s)+ ret = ""+ if out and out.type:+ ret = f": Promise<{out.type}>" if s.is_async else f": {out.type}"+ prefix = "async " if s.is_async else ""+ if _method(s):+ return f"{'private ' if typed else ''}{prefix}{_name(s)}({params}){ret} {{"+ return f"{prefix}function {_name(s)}({params}){ret} {{"+++def _ts_call(s: HelperShape) -> str:+ target = "this." if _method(s) else ""+ expr = f"{'await ' if s.is_async else ''}{target}{_name(s)}({_args(s)})"+ out = _out(s)+ if out is None:+ return expr + ";"+ keyword = ("let " if s.out_rebound else "const ") if s.out_declared else ""+ return f"{keyword}{out.name} = {expr};"+++# -- Go ----------------------------------------------------------------------+++def _go_sig(s: HelperShape) -> str:+ params = ", ".join(f"{p.name} {_type(p, 'go')}" for p in s.params)+ out = _out(s)+ ret = f" {_type(out, 'go')}" if out else ""+ recv = f"{s.receiver_decl} " if _method(s) and s.receiver_decl else ""+ return f"func {recv}{_name(s)}({params}){ret} {{"+++def _go_call(s: HelperShape) -> str:+ target = f"{s.receiver}." if _method(s) and s.receiver else ""+ expr = f"{target}{_name(s)}({_args(s)})"+ out = _out(s)+ if out is None:+ return expr+ # ``x, err :=`` in the span may only redeclare ``x``; alone it must assign.+ return f"{out.name} {'=' if s.out_written_before else ':='} {expr}"+++# -- Java / C / C++ ------------------------------------------------------------+++def _type_first(s: HelperShape, family: str) -> str:+ """``T a, U b``: Java and C / C++ write the type before the name."""+ return ", ".join(f"{_type(p, family)} {p.name}" for p in s.params)+++def _java_sig(s: HelperShape) -> str:+ out = _out(s)+ ret = _type(out, "java") if out else "void"+ static = "" if _method(s) else "static "+ return f"private {static}{ret} {_name(s)}({_type_first(s, 'java')}) {{"+++def _java_call(s: HelperShape) -> str:+ return _declared_call(s, f"{_name(s)}({_args(s)})", "var")+++def _declared_call(s: HelperShape, expr: str, inferred: str) -> str:+ """``T x = expr;`` for an output the span declared (*inferred* when its+ type is unknown), ``x = expr;`` for one declared before it."""+ out = _out(s)+ if out is None:+ return expr + ";"+ if s.out_declared:+ return f"{out.type or inferred} {out.name} = {expr};"+ return f"{out.name} = {expr};"+++def _cpp_sig(s: HelperShape) -> str:+ out = _out(s)+ if s.is_async:+ ret = TYPE_PLACEHOLDER # the coroutine's own type (a note says so)+ elif out:+ # A helper returns its value, never a reference to its own local.+ ret = (out.type or TYPE_PLACEHOLDER).rstrip("&").rstrip()+ else:+ ret = "void"+ static = "" if _method(s) else "static "+ const = " const" if _method(s) and s.receiver_decl == "const" else ""+ return f"{static}{ret} {_name(s)}({_type_first(s, 'cpp')}){const} {{"+++def _cpp_call(s: HelperShape) -> str:+ expr = f"{'co_await ' if s.is_async else ''}{_name(s)}({_args(s)})"+ # ``auto`` declares nothing before C23.+ return _declared_call(s, expr, TYPE_PLACEHOLDER if s.language == "c" else "auto")+++# -- Rust --------------------------------------------------------------------+++def _rust_borrowed(s: HelperShape, p: Slot) -> bool:+ """A known non-Copy value the host still reads after the call: passing it+ by value would move it into the helper."""+ outs = {r.name for r in s.returns}+ return bool(+ p.read_after+ and p.type+ and p.name not in outs+ and not p.type.startswith("&")+ and p.type not in _RUST_COPY+ )+++def _rust_unsure(s: HelperShape) -> list[Slot]:+ """Values read after the call whose type is unknown: they may move."""+ outs = {r.name for r in s.returns}+ return [p for p in s.params if p.read_after and not p.type and p.name not in outs]+++def _rust_self(s: HelperShape) -> str:+ """The receiver the helper borrows: the host's own when it borrows, a+ borrow when the host takes ``self`` by value (moving it into the helper+ would end the host's use of it)."""+ decl = (s.receiver_decl or "&self").strip()+ if decl.startswith("&"):+ return decl+ return "&mut self" if decl.startswith("mut") else "&self"+++def _rust_sig(s: HelperShape) -> str:+ params = [+ f"{p.name}: &{p.type}" if _rust_borrowed(s, p) else f"{p.name}: {_type(p, 'rust')}"+ for p in s.params+ ]+ if _method(s):+ params.insert(0, _rust_self(s))+ out = _out(s)+ ret = f" -> {_type(out, 'rust')}" if out else ""+ return f"{'async ' if s.is_async else ''}fn {_name(s)}({', '.join(params)}){ret} {{"+++def _rust_call(s: HelperShape) -> str:+ target = "self." if _method(s) else ""+ args = ", ".join(f"&{p.name}" if _rust_borrowed(s, p) else p.name for p in s.params)+ expr = f"{target}{_name(s)}({args}){'.await' if s.is_async else ''}"+ out = _out(s)+ if out is None:+ return expr + ";"+ if s.out_declared:+ return f"let {'mut ' if s.out_rebound else ''}{out.name} = {expr};"+ return f"{out.name} = {expr};"+++_RENDERERS = {+ "python": (_py_sig, _py_call),+ "ts": (lambda s: _ts_sig(s, True), _ts_call),+ "js": (lambda s: _ts_sig(s, False), _ts_call),+ "go": (_go_sig, _go_call),+ "java": (_java_sig, _java_call),+ "rust": (_rust_sig, _rust_call),+ "cpp": (_cpp_sig, _cpp_call),+}+++#: What the renderer adds to a stored plan, served on plan detail only.+_DETAIL_SYMBOL_KEYS = ("params", "returns", "signature_text", "notes")+++def list_plan(plan: dict) -> dict:+ """*plan* without the rendered texts and typed slots, for a list row: a+ list serves every plan, and an agent reads the texts on one plan's+ detail."""+ symbol = plan.get("new_symbol")+ if "call_site" not in plan and not (+ isinstance(symbol, dict) and any(k in symbol for k in _DETAIL_SYMBOL_KEYS)+ ):+ return plan+ out = {k: v for k, v in plan.items() if k != "call_site"}+ if isinstance(symbol, dict):+ out["new_symbol"] = {k: v for k, v in symbol.items() if k not in _DETAIL_SYMBOL_KEYS}+ return out+++def brief(name: str | None, params: list[str], returns: list[str], *, is_async: bool) -> str:+ """The helper in one language-neutral phrase for a step sentence:+ ``async _load(path) -> config, awaited at the call site``. A long+ parameter list is cut with its count; a missing name is ``<name>``."""+ shown = ", ".join(params[:4]) + (f", +{len(params) - 4} more" if len(params) > 4 else "")+ out = f"{'async ' if is_async else ''}{name or NAME_PLACEHOLDER}({shown})"+ out += f" -> {', '.join(returns[:3])}" if returns else ""+ return out + (", awaited at the call site" if is_async else "")+++__all__ = [+ "NAME_PLACEHOLDER",+ "PARAM_MODES",+ "TYPE_PLACEHOLDER",+ "HelperShape",+ "ParamMode",+ "Rendered",+ "Slot",+ "brief",+ "list_plan",+ "private_name",+ "render",+ "symbol_params",+]diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex c1a21ec2f..dfffb254a 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -79,6 +79,24 @@ export interface PlanCoChangePartner {commits: number;}+/** An Extract Method helper parameter's role: ``inout`` when the helper also+ * returns the value's new state. Mirrors ``refactoring.render.PARAM_MODES``. */+export type ExtractParamMode = "in" | "inout";++/** One helper parameter or output, with its declared type (null: unknown). */+export interface ExtractSlot {+ name: string;+ type: string | null;+ mode?: ExtractParamMode;+}++/** The statement that replaces an Extract Method span. Spec text for whoever+ * applies the plan; Repowise never applies it. */+export interface ExtractCallSite {+ replace_span: { start: number; end: number };+ new_text: string;+}+export interface RefactoringPlan {id: string;refactoring_type: RefactoringType | string;diff --git a/packages/ui/__tests__/refactoring/extract-method-types.test.ts b/packages/ui/__tests__/refactoring/extract-method-types.test.tsindex 079c8820a..96e89c2f5 100644--- a/packages/ui/__tests__/refactoring/extract-method-types.test.ts+++ b/packages/ui/__tests__/refactoring/extract-method-types.test.ts@@ -4,6 +4,7 @@ import {generatedVerdict,planSynopsis,planWins,+ slotLabel,type GeneratedCode,type RefactoringPlan,} from "../../src/refactoring/types";@@ -91,6 +92,33 @@ describe("extract_method plan accessors", () => {]);});+ it("reads the rendered signature, call site and typed params, null before them", () => {+ const old = extractMethodPlan(extractMethodPlanFixture());+ expect([old.signature_text, old.call_site, old.typed_params]).toEqual([null, null, []]);+ const em = extractMethodPlan(+ extractMethodPlanFixture({+ plan: {+ span: { start: 30, end: 48 },+ params: ["records"],+ returns: ["average"],+ new_symbol: {+ kind: "function",+ params: [{ name: "records", type: "list[int]", mode: "in" }],+ returns: [{ name: "average", type: null }],+ signature_text: "def _compute_average(records: list[int]):",+ },+ call_site: { replace_span: { start: 30, end: 48 }, new_text: "average = _compute_average(records)" },+ },+ }),+ );+ expect(em.signature_text).toBe("def _compute_average(records: list[int]):");+ expect(em.call_site?.new_text).toBe("average = _compute_average(records)");+ expect(em.typed_params[0]).toEqual({ name: "records", type: "list[int]", mode: "in" });+ expect(em.typed_params.map(slotLabel)).toEqual(["records: list[int]"]);+ expect(em.typed_returns.map(slotLabel)).toEqual(["average"]);+ expect(em.notes).toEqual([]);+ });+it("returns a null span when the plan omits it", () => {const em = extractMethodPlan(extractMethodPlanFixture({ plan: { params: [], returns: [] } }));expect(em.span).toBeNull();diff --git a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.tsindex 2ec787f2c..065142762 100644--- a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts+++ b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts@@ -91,9 +91,9 @@ describe("extract_method suggested_name reaches the rendered prompt", () => {expect(prompt).not.toContain("a clearly named helper");});- it("keeps the generic fallback for a plan stored before names were computed", () => {+ it("asks the agent to fill the name placeholder when no name was anchored", () => {const prompt = buildRefactoringPlanPrompt({ plan: methodPlan(null) });- expect(prompt).toContain("a clearly named helper");+ expect(prompt).toContain("`<name>` (name it for what the lines do)");expect(extractMethodPlan(methodPlan(null)).suggested_name).toBeNull();});diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.tsindex 88f8e1aa2..9475314f8 100644--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts@@ -11,6 +11,7 @@ import {extractClassGroups,extractHelperOccurrences,extractMethodPlan,+ HELPER_NAME_PLACEHOLDER,helperSite,moveTarget,splitGroups,@@ -66,10 +67,20 @@ function extractMethodSteps(plan: RefactoringPlan): string {if (!em.span) return "Extract the indicated slice into a helper method.";const params = em.params.length ? em.params.join(", ") : "(none)";const returns = em.returns.length ? em.returns.join(", ") : "(nothing)";- const name = em.suggested_name ?? "a clearly named helper";+ const name = em.suggested_name ?? HELPER_NAME_PLACEHOLDER;+ const rendered = [+ ...(em.signature_text ? [`- **New helper:** \`${em.signature_text}\``] : []),+ ...(em.call_site+ ? [`- **Replace lines ${em.span.start}–${em.span.end} with:** \`${em.call_site.new_text}\``]+ : []),+ ...em.notes.map((note) => `- **Note:** ${note}`),+ ];return [- `Extract lines ${em.span.start}–${em.span.end} of \`${plan.target_symbol}\` into ${name}:`,+ `Extract lines ${em.span.start}–${em.span.end} of \`${plan.target_symbol}\` into \`${name}\`${+ em.suggested_name ? "" : " (name it for what the lines do)"+ }:`,"",+ ...rendered,`- **Parameters (in):** ${params}`,`- **Returns (out):** ${returns}`,...(em.needs_async ? ["- **Async:** the span awaits, so declare the helper async and await its call"] : []),diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsxindex 6e6d1fcc6..2cbcc7467 100644--- a/packages/ui/src/refactoring/plan-detail.tsx+++ b/packages/ui/src/refactoring/plan-detail.tsx@@ -1,6 +1,8 @@"use client";import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";+import { getLanguageFromPath } from "../c4/panels/CodeViewer";+import { HighlightedCodeBlock } from "../shared/code-block";import { ProvenancePathList } from "../shared/provenance-path-list";import {blastFiles,@@ -11,9 +13,12 @@ import {extractHelperOccurrences,extractMethodPlan,extractMethodSignature,+ HELPER_NAME_PLACEHOLDER,+ HELPER_TYPE_PLACEHOLDER,helperSite,moveTarget,performancePlanDetail,+ slotLabel,splitBlast,splitGroups,splitResidual,@@ -430,6 +435,11 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailPropconst lines = em.span ? em.span.end - em.span.start + 1 : 0;const ccn = Number(plan.evidence?.ccn_removed ?? 0);const sig = extractMethodSignature(em);+ // The one extension-to-language map in the UI lives in the code viewer.+ const codeLanguage = getLanguageFromPath(plan.file_path);+ // Typed where the plan has them; a method's receiver is not a parameter.+ const inLabels = em.typed_params.length ? em.typed_params.map(slotLabel) : em.params;+ const outLabels = em.typed_returns.length ? em.typed_returns.map(slotLabel) : em.returns;return (<div className="space-y-3">{hideIntro ? null : (@@ -462,23 +472,59 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp) : null}<div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">- <div className="mb-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">- Inferred signature- </div>- <code className="block break-all font-mono text-xs text-[var(--color-text-primary)]">- {sig}- </code>+ {em.signature_text ? (+ <>+ <HighlightedCodeBlock+ code={em.signature_text}+ language={codeLanguage}+ label="New helper"+ compact+ className="my-0"+ />+ {em.call_site ? (+ <HighlightedCodeBlock+ code={em.call_site.new_text}+ language={codeLanguage}+ label={`Replaces lines ${em.call_site.replace_span.start}–${em.call_site.replace_span.end}`}+ compact+ className="mb-0 mt-2"+ />+ ) : null}+ {[em.signature_text, em.call_site?.new_text ?? ""].some(+ (t) => t.includes(HELPER_NAME_PLACEHOLDER) || t.includes(HELPER_TYPE_PLACEHOLDER),+ ) ? (+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">+ Replace {HELPER_NAME_PLACEHOLDER} with a name for what the lines do, and any{" "}+ {HELPER_TYPE_PLACEHOLDER} with the value's type.+ </p>+ ) : null}+ {em.notes.map((note) => (+ <p key={note} className="mt-2 text-2xs text-[var(--color-text-tertiary)]">+ {note}+ </p>+ ))}+ </>+ ) : (+ <>+ <div className="mb-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">+ Inferred signature+ </div>+ <code className="block break-all font-mono text-xs text-[var(--color-text-primary)]">+ {sig}+ </code>+ </>+ )}<div className="mt-2 flex flex-wrap gap-3 text-2xs text-[var(--color-text-tertiary)]"><span>In (params):{" "}<span className="text-[var(--color-text-secondary)]">- {em.params.length ? em.params.join(", ") : "none"}+ {inLabels.length ? inLabels.join(", ") : "none"}</span></span><span>Out (return):{" "}<span className="text-[var(--color-text-secondary)]">- {em.returns.length ? em.returns.join(", ") : "none"}+ {outLabels.length ? outLabels.join(", ") : "none"}</span></span></div>diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.tsindex ba09d7a4d..e3c993e03 100644--- a/packages/ui/src/refactoring/types.ts+++ b/packages/ui/src/refactoring/types.ts@@ -8,6 +8,8 @@*/import type {+ ExtractCallSite,+ ExtractSlot,GeneratedCode,RefactoringPlan,RefactoringType,@@ -172,6 +174,17 @@ export interface ExtractMethodPlan {assigns: string[] | null;/** Why the helper cannot share the receiver as it is (a judgment call). */receiver_hazard: "receiver_unbound" | "receiver_copy_written" | null;+ /** Typed parameters and outputs; empty for a plan stored before them. */+ typed_params: ExtractSlot[];+ typed_returns: ExtractSlot[];+ /** The helper's header in the file's language, and the statement replacing+ * the span. Null when the helper's form is unknown or the plan predates it.+ * `<name>` / `<type>` are placeholders to fill. */+ signature_text: string | null;+ call_site: ExtractCallSite | null;+ /** What the texts cannot say (a value that may move, a call the host+ * cannot await). */+ notes: string[];}const RECEIVER_HAZARDS = ["receiver_unbound", "receiver_copy_written"] as const;@@ -195,12 +208,35 @@ export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {uses_receiver: typeof sym.uses_receiver === "boolean" ? sym.uses_receiver : null,assigns: Array.isArray(sym.assigns) ? (sym.assigns as string[]) : null,receiver_hazard: RECEIVER_HAZARDS.find((h) => h === p.receiver_hazard) ?? null,+ typed_params: Array.isArray(sym.params) ? (sym.params as ExtractSlot[]) : [],+ typed_returns: Array.isArray(sym.returns) ? (sym.returns as ExtractSlot[]) : [],+ signature_text: typeof sym.signature_text === "string" ? sym.signature_text : null,+ call_site: callSite(p.call_site),+ notes: Array.isArray(sym.notes) ? (sym.notes as string[]) : [],};}-/** The helper an extraction proposes, as one line: `async name(a, b) -> c`. */+function callSite(raw: unknown): ExtractCallSite | null {+ const rec = (raw ?? null) as Record<string, unknown> | null;+ return rec && typeof rec.new_text === "string" && rec.replace_span && typeof rec.replace_span === "object"+ ? (rec as unknown as ExtractCallSite)+ : null;+}++/** The placeholders a plan's texts use for a name or type the code does not+ * give. Mirror ``refactoring.render.NAME_PLACEHOLDER`` / ``TYPE_PLACEHOLDER``. */+export const HELPER_NAME_PLACEHOLDER = "<name>";+export const HELPER_TYPE_PLACEHOLDER = "<type>";++/** A typed slot as `name: type`, or the bare name when the type is unknown. */+export function slotLabel(slot: ExtractSlot): string {+ return slot.type ? `${slot.name}: ${slot.type}` : slot.name;+}++/** The helper an extraction proposes, as one line: `async name(a, b) -> c`.+ * For a plan stored before the server rendered `signature_text`. */export function extractMethodSignature(em: ExtractMethodPlan): string {- const name = em.suggested_name ?? "helper";+ const name = em.suggested_name ?? HELPER_NAME_PLACEHOLDER;const returns = em.returns.length ? ` -> ${em.returns.join(", ")}` : "";return `${em.needs_async ? "async " : ""}${name}(${em.params.join(", ")})${returns}`;}diff --git a/tests/unit/health/test_extract_method_receiver.py b/tests/unit/health/test_extract_method_receiver.pyindex a6aac9383..e986597e0 100644--- a/tests/unit/health/test_extract_method_receiver.py+++ b/tests/unit/health/test_extract_method_receiver.py@@ -120,7 +120,11 @@ def test_python_span_writing_self_fields_is_a_method_and_names_them():def test_python_plan_carries_new_symbol():plans = {p.plan["span"]["start"]: p for p in _plans("python", "py", _PY)}(plan,) = plans.values()- sym = plan.plan["new_symbol"]+ sym = {+ k: v+ for k, v in plan.plan["new_symbol"].items()+ if k not in ("params", "returns", "signature_text")+ }if plan.plan["span"]["start"] >= 12:assert sym == {"kind": "method",diff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.pynew file mode 100644index 000000000..7d421657b--- /dev/null+++ b/tests/unit/health/test_extract_method_render.py@@ -0,0 +1,400 @@+"""An Extract Method plan writes out the helper's header and its call.++An agent applying a plan used to rebuild the helper from bare names: whether+it is a method, async, which types its parameters take, how the call declares+the output. The plan now carries ``new_symbol.signature_text`` and+``call_site.new_text`` in the file's language, typed parameters read off+their declarations, and ``<name>`` / ``<type>`` placeholders where the code+anchors neither. Spec text only: nothing here edits a file.+"""++from __future__ import annotations++import pathlib+import re+import textwrap+from dataclasses import dataclass++import pytest++from repowise.core.analysis.health.dataflow import (+ Extraction,+ analyze_file,+ get_defuse_dialect,+)+from repowise.core.analysis.health.refactoring import extract_method as em+from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector+from repowise.core.analysis.health.refactoring.models import (+ RefactoringContext,+ RefactoringSuggestion,+)+from repowise.core.analysis.health.refactoring.render import (+ PARAM_MODES,+ HelperShape,+ Slot,+ private_name,+ render,+ symbol_params,+)+++@dataclass+class _Finding:+ biomarker_type: str+ function_name: str+ line_start: int+ health_impact: float+++def _functions(language: str, ext: str, src: str):+ from repowise.core.ingestion.parser import _get_language++ if _get_language(language) is None:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ res = analyze_file(f"m.{ext}", language, textwrap.dedent(src).encode(), flagged_only=False)+ if res.stats.functions_seen == 0:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ return res.functions+++# One loop removing three decision points; the guard's ``return`` keeps any+# span from running on into the filler, so the loop is the one offered.+# ``{call}`` awaits or not.+_PY = """+class Store:+ async def run(self, items: list[int], limit: int) -> int:+ total: int = 0+ for i in items:+ if i > limit:+ total += i+ elif i < 0:+ total -= i+ else:+ {call}+ print(i)+ print(i)+ if limit is None:+ return 0+{tail} return total+"""+++def _py_plan(call: str = "await self.flush(i)"):+ tail = "".join(f" print({n})\n" for n in range(14))+ src = _PY.replace("{call}", call).replace("{tail}", tail)+ fns = _functions("python", "py", src)+ ctx = RefactoringContext(+ file_path="m.py",+ language="python",+ nloc=100,+ findings=[_Finding("complex_method", f.name, f.start_line, 1.5) for f in fns],+ function_analyses=fns,+ )+ (plan,) = ExtractMethodDetector().detect(ctx)+ return plan.plan+++def test_python_plan_carries_an_awaited_method_header_and_call():+ plan = _py_plan()+ sym = plan["new_symbol"]+ assert plan["suggested_name"] is None # nothing anchors a name here+ assert sym["signature_text"] == (+ "async def <name>(self, items: list[int], limit: int) -> int:"+ )+ assert plan["call_site"] == {+ "replace_span": plan["span"],+ "new_text": "total = await self.<name>(items, limit)",+ }+ # The receiver is not a parameter of a method.+ assert sym["params"] == [+ {"name": "items", "type": "list[int]", "mode": "in"},+ {"name": "limit", "type": "int", "mode": "in"},+ ]+ assert sym["returns"] == [{"name": "total", "type": "int"}]+++def test_a_span_that_does_not_await_is_not_awaited():+ plan = _py_plan("print(-i)")+ assert plan["new_symbol"]["signature_text"].startswith("def <name>(items: list[int]")+ assert "await" not in plan["call_site"]["new_text"]+++def test_python_names_take_the_private_form():+ assert private_name("python", "compute_total") == "_compute_total"+ assert private_name("python", "_already") == "_already"+ assert private_name("go", "computeTotal") == "computeTotal"+ assert private_name("python", None) is None+++def _shape(language: str, **kw) -> HelperShape:+ base = dict(+ language=language,+ name="loadTotals",+ kind="method",+ is_async=False,+ params=(Slot("items", "T1"), Slot("limit", None)),+ returns=(Slot("total", None),),+ )+ return HelperShape(**{**base, **kw})+++ ("shape", "sig", "call"),+ [+ (+ _shape("typescript", is_async=True, out_declared=True, returns=(Slot("total", "number"),)),+ "private async loadTotals(items: T1, limit): Promise<number> {",+ "const total = await this.loadTotals(items, limit);",+ ),+ (+ _shape("javascript", kind="function", out_declared=True, out_rebound=True),+ "function loadTotals(items: T1, limit) {",+ "let total = loadTotals(items, limit);",+ ),+ (+ _shape("go", receiver="s", receiver_decl="(s *S)", out_declared=True),+ "func (s *S) loadTotals(items T1, limit <type>) <type> {",+ "total := s.loadTotals(items, limit)",+ ),+ (+ # ``x, err :=`` in the span redeclared ``total``; alone it assigns.+ _shape("go", receiver="s", receiver_decl="(s *S)", out_declared=True,+ out_written_before=True),+ "func (s *S) loadTotals(items T1, limit <type>) <type> {",+ "total = s.loadTotals(items, limit)",+ ),+ (+ _shape("java", kind="function", out_declared=True),+ "private static <type> loadTotals(T1 items, <type> limit) {",+ "var total = loadTotals(items, limit);",+ ),+ (+ _shape("rust", is_async=True, receiver_decl="mut self", out_declared=True, out_rebound=True),+ "async fn loadTotals(&mut self, items: T1, limit: <type>) -> <type> {",+ "let mut total = self.loadTotals(items, limit).await;",+ ),+ (+ _shape("cpp", returns=(Slot("total", "int"),), out_declared=True),+ "int loadTotals(T1 items, <type> limit) {",+ "int total = loadTotals(items, limit);",+ ),+ (+ _shape("cpp", receiver_decl="const", returns=(Slot("total", "const Row&"),)),+ "const Row loadTotals(T1 items, <type> limit) const {",+ "total = loadTotals(items, limit);",+ ),+ (+ _shape("c", kind="function", out_declared=True),+ "static <type> loadTotals(T1 items, <type> limit) {",+ "<type> total = loadTotals(items, limit);",+ ),+ (+ _shape("cpp", kind="function", name=None, returns=()),+ "static void <name>(T1 items, <type> limit) {",+ "<name>(items, limit);",+ ),+ (+ _shape("python", kind="method", receiver="cls", name="_load", returns=()),+ "@classmethod\ndef _load(cls, items: T1, limit):",+ "cls._load(items, limit)",+ ),+ ],+)+def test_each_language_writes_its_own_header_and_call(shape, sig, call):+ assert render(shape)[:2] == (sig, call)+++def test_rust_borrows_a_value_the_host_reads_after_the_call():+ shape = _shape(+ "rust",+ kind="function",+ params=(+ Slot("rows", "Vec<Row>", read_after=True),+ Slot("n", "usize", read_after=True),+ Slot("cfg", None, read_after=True),+ Slot("tmp", "String"),+ ),+ returns=(),+ )+ sig, call, notes = render(shape)+ assert sig == "fn loadTotals(rows: &Vec<Row>, n: usize, cfg: <type>, tmp: String) {"+ assert call == "loadTotals(&rows, n, cfg, tmp);"+ assert notes == (+ "Pass cfg by reference (&) unless the type is Copy: the caller still reads it "+ "after the call.",+ )+++def test_an_awaiting_span_in_a_host_that_is_not_async_gets_no_call():+ out = render(_shape("python", is_async=True, async_host=False, receiver="self"))+ assert out.signature.startswith("async def loadTotals(self")+ assert out.call is None+ assert "not async" in out.notes[0]+++def test_a_cpp_coroutine_helper_leaves_its_return_type_to_fill():+ out = render(_shape("cpp", is_async=True, returns=(Slot("total", "int"),), out_declared=True))+ assert out.signature == "<type> loadTotals(T1 items, <type> limit) {"+ assert out.call == "int total = co_await loadTotals(items, limit);"+ assert out.notes == ("Give the helper the coroutine return type the caller co_awaits.",)+++def test_cpp_const_member_function_is_named_by_its_dialect():+ src = "class A { int f(int a) const { int x = a; return x; } };"+ (fn,) = _functions("cpp", "cpp", src)+ assert get_defuse_dialect("cpp").receiver_decl(fn.fn_node) == "const"+ src = "class A { int f(int a) { int x = a; return x; } };"+ (fn,) = _functions("cpp", "cpp", src)+ assert get_defuse_dialect("cpp").receiver_decl(fn.fn_node) is None+++def test_types_are_found_for_a_non_ascii_name():+ """Tree points count bytes, so the lookup spans the name's bytes."""+ src = """+ def f(rows):+ zähler: int = 0+ for r in rows:+ zähler += 1+ return zähler+ """+ (fn,) = _functions("python", "py", src)+ span = Extraction(4, 5, ("rows", "zähler"), ("zähler",), slice_nloc=2, ccn_removed=1)+ assert em._declared_types(fn, span, get_defuse_dialect("python")) == {"zähler": "int"}+++def test_an_unknown_helper_form_writes_no_text():+ """``kind`` None: the span may reach its object through a name a function+ would not have, so a function header would be a confident wrong spec."""+ assert render(_shape("python", kind=None)) is None+ assert render(_shape("kotlin")) is None+++def test_a_value_the_helper_also_returns_is_inout():+ params = symbol_params((Slot("acc", "int"), Slot("xs")), (Slot("acc", "int"),))+ assert [p["mode"] for p in params] == ["inout", "in"]+++_TYPED_SOURCES = {+ "python": ("py", "def f(a: int, b, c: list[str] = None):\n x: dict[str, int] = {}\n"),+ "typescript": ("ts", "function f(a: number, b?: string, c = 3) { const x: Map<string, number> = new Map(); }"),+ "go": ("go", "package m\nfunc f(a, b int, c string) { var x []string; y := 2 }"),+ "java": ("java", "class C { void f(final int a, String[] b, int c) { int x = 3; var y = 2; } }"),+ "rust": ("rs", "fn f(a: i32, mut b: &mut Vec<u8>, (c, d): (i32, i32)) { let x: u64 = 3; }"),+ "cpp": ("cpp", "void f(int a, const char *b, std::vector<int>& c) { auto x = 2; int *p = nullptr; }"),+}+_EXPECTED_TYPES = {+ "python": {"a": "int", "b": None, "c": "list[str]", "x": "dict[str, int]"},+ "typescript": {"a": "number", "b": "string", "c": None, "x": "Map<string, number>"},+ "go": {"a": "int", "b": "int", "c": "string", "x": "[]string", "y": None},+ "java": {"a": "int", "b": "String[]", "c": "int", "x": "int", "y": None},+ "rust": {"a": "i32", "b": "&mut Vec<u8>", "c": None, "d": None, "x": "u64"},+ "cpp": {"a": "int", "b": "const char*", "c": "std::vector<int>&", "x": None, "p": "int*"},+}++[email protected]("language", sorted(_TYPED_SOURCES))+def test_declared_types_are_read_off_the_parse(language: str):+ ext, src = _TYPED_SOURCES[language]+ (fn,) = _functions(language, ext, src)+ dialect = get_defuse_dialect(language)+ found = {}+ for d in fn.def_use.definitions:+ row = d.line - 1+ node = fn.fn_node.descendant_for_point_range((row, d.column), (row, d.column + len(d.var)))+ found[d.var] = dialect.declared_type(node)+ assert {k: found.get(k) for k in _EXPECTED_TYPES[language]} == _EXPECTED_TYPES[language]+++def test_a_type_comes_from_the_latest_typed_write_before_the_span_end():+ src = """+ def f(rows):+ count: int = 0+ for r in rows:+ if r:+ count += 1+ elif r is None:+ count -= 1+ print(r)+ print(1)+ print(2)+ print(3)+ print(4)+ return count+ """+ (fn,) = _functions("python", "py", src)+ # The loop: ``count`` is read and written there, last typed at line 3.+ span = Extraction(4, 9, ("count", "rows"), ("count",), slice_nloc=6, ccn_removed=3)+ assert em._declared_types(fn, span, get_defuse_dialect("python")) == {"count": "int"}+++def test_param_modes_match_the_wire_type():+ src = (pathlib.Path(__file__).resolve().parents[3] / "packages/types/src/refactoring.ts").read_text(+ encoding="utf-8"+ )+ match = re.search(r"export type ExtractParamMode =(.*?);", src, re.DOTALL)+ assert match+ assert set(re.findall(r'"([a-z_]+)"', match.group(1))) == set(PARAM_MODES)+++def test_list_rows_leave_the_texts_to_plan_detail():+ """A list serves every plan, so its rows stay as they were before the+ texts existed; one plan's detail carries them."""+ import dataclasses+ import json++ from repowise.core.analysis.health.refactoring.recommendations import build_recommendations++ plan = _py_plan()+ suggestion = RefactoringSuggestion(+ refactoring_type="extract_method",+ file_path="m.py",+ target_symbol="run",+ line_start=3,+ line_end=30,+ plan=plan,+ evidence={"slice_nloc": 9, "ccn_removed": 3},+ impact_delta=1.0,+ effort_bucket="S",+ blast_radius={"scope": "local"},+ confidence="high",+ )+ before = dict(plan)+ before.pop("call_site")+ before["new_symbol"] = {+ k: v+ for k, v in plan["new_symbol"].items()+ if k not in ("params", "returns", "signature_text")+ }+ (with_texts,) = build_recommendations([suggestion])+ (without,) = build_recommendations([dataclasses.replace(suggestion, plan=before)])+ assert json.dumps(with_texts.as_dict()) == json.dumps(without.as_dict())+ detail = with_texts.detail_dict()["plan"]+ assert detail["call_site"] == plan["call_site"]+ assert detail["new_symbol"]["signature_text"] == plan["new_symbol"]["signature_text"]+ # The stored plan itself is untouched by the list projection.+ assert "call_site" in suggestion.plan+++def test_cli_json_plan_rows_leave_the_texts_out():+ from repowise.cli.commands.health_cmd.refactoring_targets import _list_row++ plan = _py_plan()+ row = _list_row({"id": "p", "plan": plan})+ assert "call_site" not in row["plan"]+ assert "signature_text" not in row["plan"]["new_symbol"]+ assert row["plan"]["new_symbol"]["kind"] == plan["new_symbol"]["kind"]+ assert _list_row({"id": "q", "plan": None}) == {"id": "q", "plan": None}+++def test_read_after_names_the_inputs_the_host_still_uses():+ src = """+ def f(rows, cfg):+ total = 0+ for r in rows:+ total += r+ print(cfg, total)+ return total+ """+ (fn,) = _functions("python", "py", src)+ span = Extraction(4, 5, ("cfg", "rows", "total"), ("total",), slice_nloc=2, ccn_removed=1)+ assert em._read_after(fn, span) == {"cfg", "total"}diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 0d980ae7d..acfa02e95 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -98,7 +98,9 @@ def test_text_quotes_the_stored_numbers() -> None:)assert ("size", "CCN 44, 50 lines, nests 4 deep") in [(f.label, f.value) for f in core.facts]assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"- assert core.action.steps[1].text == "Extract lines 40-41 of run into a helper"+ assert core.action.steps[1].text == (+ "Extract lines 40-41 of run into <name>(); name it for what the lines do"+ )# The model's credit is the gain, with one decimal; the builder does not re-judge it.assert (core.gain.value, core.gain.text) == (2.0, "+2.0 health on this file")assert core.source.plan_ids == ("refac2_big", "refac2_tiny")diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.pyindex 80ddf3ab2..1cc3c22de 100644--- a/tests/unit/health/test_fix_first_precision.py+++ b/tests/unit/health/test_fix_first_precision.py@@ -577,5 +577,5 @@ def test_a_span_that_awaits_is_extracted_into_an_awaited_async_helper() -> None:"async load_rows(db) -> rows, awaited at the call site")assert text.signature(None, ["db"], [], is_async=True) == (- "an async helper taking (db), awaited at the call site"+ "async <name>(db), awaited at the call site; name it for what the lines do")diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex 169857cf7..b5cbe1b14 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -585,6 +585,7 @@ def test_detector_emits_suggestion_for_flagged_function():"suggested_name","needs_async","new_symbol",+ "call_site",}assert s.plan["needs_async"] is False# A module-level function: the helper is a plain function too.@@ -594,7 +595,11 @@ def test_detector_emits_suggestion_for_flagged_function():"receiver": None,"uses_receiver": False,"assigns": [],+ "params": s.plan["new_symbol"]["params"],+ "returns": s.plan["new_symbol"]["returns"],+ "signature_text": s.plan["new_symbol"]["signature_text"],}+ assert s.plan["call_site"]["replace_span"] == s.plan["span"]assert set(s.plan["span"]) == {"start", "end"}assert set(s.evidence) == {"slice_nloc", "ccn_removed"}# A categorical claim, not a count: extraction is local, so there is nothing@@ -615,7 +620,8 @@ def test_plan_carries_a_computed_name_not_a_hardcoded_none():# The slice's single OUT value is ``average``, so the span is by# construction the code that computes it.assert s.plan["returns"] == ["average"]- assert s.plan["suggested_name"] == "compute_average"+ # In Python's private form.+ assert s.plan["suggested_name"] == "_compute_average"class _Extraction:@@ -697,7 +703,7 @@ def test_suggested_name_keeps_the_out_values_own_casing():@pytest.mark.parametrize(("language", "expected"),[- ("python", "compute_average"),+ ("python", "_compute_average"),("rust", "compute_average"),("cpp", "compute_average"),("java", "computeAverage"),diff --git a/tests/unit/health/test_refactoring_extract_method_naming.py b/tests/unit/health/test_refactoring_extract_method_naming.pyindex 23cf577b7..ab33480de 100644--- a/tests/unit/health/test_refactoring_extract_method_naming.py+++ b/tests/unit/health/test_refactoring_extract_method_naming.py@@ -37,7 +37,9 @@ def _functions(language: str, ext: str, src: str):def _names(src: str, language: str = "python", ext: str = "py") -> list[tuple[str, str | None]]:- """``(function, suggested_name)`` per plan, every function flagged."""+ """``(function, suggested_name)`` per plan, every function flagged. The+ name is read before the private form (Python's ``_``), which+ ``test_extract_method_render`` pins."""fns = _functions(language, ext, src)ctx = RefactoringContext(file_path=f"m.{ext}",@@ -47,7 +49,11 @@ def _names(src: str, language: str = "python", ext: str = "py") -> list[tuple[stfunction_analyses=fns,)plans = sorted(ExtractMethodDetector().detect(ctx), key=lambda s: s.line_start or 0)- return [(s.target_symbol, s.plan["suggested_name"]) for s in plans]+ return [(s.target_symbol, _starting_name(s.plan["suggested_name"], language)) for s in plans]+++def _starting_name(name: str | None, language: str) -> str | None:+ return name.removeprefix("_") if name and language == "python" else namedef _name(src: str, language: str = "python", ext: str = "py") -> str | None: