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): refuse flat record builders, group a split's plans, name every helper (#3421)
Raghav Chamadiya80e7fece6c44
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 97e16798e..1767a667d 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -103,7 +103,9 @@ On an opportunity, each step carries `applicability`: `mechanical` (onlyextractions qualify) or `judgment`, with the facts behind the call. When anearlier step moves a symbol to another file, the later step carries`relocated_by`: its stored location is where the symbol was before, so find it-again before applying.+again before applying. In the plan list a Split File plan stands for the plans+it relocates in the same file: its row lists them as `relocates`, and they take no+rows of their own.Plan detail also lists `risks`, one sentence each, to read before applying theplan: an accepted decision that governs the file, callers or importers of what@@ -145,8 +147,9 @@ Fix first item leaves it out and says how many steps it held back; the full plankeeps them. Code only moves within a language family,so Java, Kotlin and Scala are separate. A callback is named after the call it ispassed to. An Extract Method helper is named from a stage label, a banner comment,-or `compute_<value>` when the span has no outside effects. A name already taken-where the helper lands is dropped, so a `null` name means you name the helper.+or `compute_<value>` when the span has no outside effects; otherwise it is the host+function's name plus what the span handles, such as `render_card_directive`. A+name already taken where the helper lands is skipped for the next candidate.An empty list means no detector found work that clears its gates. It does not meanthe code needs no attention: check the findings in@@ -231,7 +234,10 @@ Most plans answer a health finding, so per-path marker rules inwrite in an `else` arm or a `try` body that may raise first.- Extract Method skips spans too small to matter and spans that would carry theoriginal finding into the helper. A component whose branching is mostly in its- markup gets no extraction.+ markup gets no extraction, and neither does a function that only fills one+ value field by field behind independent guards (summary rows, query+ parameters, optional settings), since splitting it simplifies neither half.+ Its finding records why in `details.extract_method_refused`.- An Extract Method span must remove at least two decision points, hold at least8 code lines, cover at most 60% of the function's lines, and not start on thedocstring. When the best span misses one of these, only a span that does notdiff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex d3d43ca77..90b5b8485 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -377,7 +377,7 @@ Provisional finding types appear only with `include=["unverified"]`, each marked`get_health(opportunity_id="refop...")` returns full steps, member plans, the validation profile and `next_actions`; `only=["refactoring_evidence"]` with `cursor` pages the evidence. `found` says whether the id matched; `status` is `open`, `acknowledged`, `resolved` or `false_positive`. `refactoring_summary` rolls up by type, effort, confidence and lifecycle.-`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`) and `relocated_by` when set; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation), and for a plan the index resolved, its `payoff`. `refactoring_plans_total` counts plans in scope, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).+`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`), `relocated_by` when set, and on a Split File plan `relocates`, the ids of the plans it relocates, which it stands for instead of listing them; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation), and for a plan the index resolved, its `payoff`. `refactoring_plans_total` and the page cursor count plans in scope, so a page that holds a Split File row can list fewer rows than the plans it covers, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).### Performancediff --git a/packages/core/src/repowise/core/analysis/health/dataflow/span.py b/packages/core/src/repowise/core/analysis/health/dataflow/span.pyindex 8f1d8f709..ecaf764f9 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/span.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/span.py@@ -41,11 +41,18 @@ def span_statements(def enclosing_with(stmts: list[Node], lmap: LanguageNodeMap) -> Node | None:"""The ``with`` statement whose whole body *stmts* is, else ``None``: a spanlifted out of ``with timed(...):`` is the block that header labels."""+ holder = body_holder(stmts)+ return holder if holder is not None and holder.type in lmap.with_kinds else None+++def body_holder(stmts: list[Node]) -> Node | None:+ """The statement whose whole body *stmts* is (a ``with``, an ``if`` arm, a+ loop), else ``None``."""if not stmts:return Noneblock = stmts[0].parentholder = block.parent if block is not None else None- if holder is None or holder.type not in lmap.with_kinds:+ if holder is None:return Nonecode = [c for c in block.named_children if not is_comment(c)]inside = [s for s in stmts if not is_comment(s)]diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.pyindex 72399f5d0..8de0f9a2f 100644--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py@@ -82,6 +82,7 @@ _DERIVED_DETAIL_KEYS = frozenset("gated_off","loop_line","deepest_block",+ "extract_method_refused",})"""Keys version 1 left out of its hash; only :func:`legacy_finding_public_id` reads it."""diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/declarative.py b/packages/core/src/repowise/core/analysis/health/refactoring/declarative.pynew file mode 100644index 000000000..7859a79d0--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/declarative.py@@ -0,0 +1,235 @@+"""Whether a function is a flat record builder, whose complexity no helper splits.++A function that fills one value field by field (rows added, keys set, a field+copied when present, a query parameter set when given) earns its CCN from the+guard on each field and the conditionals in each value. The guards are+independent of each other, so lifting a run of them into a helper moves part+of the list without making either half simpler to read.++The shape, read off the tree in any language the slicer serves: every+statement writes the same one name (``x.f = v`` / ``x[k] = v``, ``delete x.f``,+or a call on a parameter or local, ``rows.append(...)``) or binds a local once,+and the only control flow is a guard around such statements (an ``if`` chain,+a ``try``, a loop over rows) or a guard that returns. A second written name, a+call on a module or imported name (``print``, ``logger.info``, ``res.send``+on no local), a loop in a loop, a callback (whose body is logic the statement+only registers), a ``break`` / ``continue`` or a ``switch`` is logic, and the+function is not flat.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import TYPE_CHECKING++from ..complexity.ast_utils import _find_function_entry_name+from ..complexity.nloc import is_string_stmt+from ..dataflow.effects import binding_target, bound_names+from ..dataflow.span import is_comment++if TYPE_CHECKING:+ from collections.abc import Collection++ from tree_sitter import Node++ from ..complexity.languages import LanguageNodeMap++_EXPR_STMT = "expression_statement"+_EMPTY_KINDS = frozenset({"pass_statement", "empty_statement"})+_ELSE_KINDS = frozenset({"else_clause", "elif_clause"})+_FINALLY = "finally_clause"+_ACCESS_FIELDS = ("object", "value", "operand", "argument", "array", "function")+# ``function`` in most grammars; Java's method call names its ``object``.+_CALLEE_FIELDS = ("function", "object")+_CALL_KINDS = frozenset({"call", "call_expression", "method_invocation"})+_NAME_TARGETS = frozenset({"identifier", "pattern_list", "tuple_pattern"})+# Fewer writes than this is a short function with a few guards, not a builder.+_MIN_WRITES = 3+++@dataclass(slots=True)+class _Census:+ lmap: LanguageNodeMap+ roots: set[str] = field(default_factory=set)+ call_roots: set[str] = field(default_factory=set)+ writes: int = 0+ bound: set[str] = field(default_factory=set)+ in_loop: bool = False++ def bind(self, names: list[str]) -> bool:+ """Count a local; one bound twice is state the guards update, not a field."""+ if not names or self.bound.intersection(names):+ return False+ self.bound.update(names)+ return True+++def declarative_flat(+ fn_node: Node | None, lmap: LanguageNodeMap, params: Collection[str] = ()+) -> bool:+ """True when *fn_node*'s body is a flat record builder (module docstring).+ *params* are its parameter names, the receivers a call may write through."""+ body = fn_node.child_by_field_name("body") if fn_node is not None else None+ if body is None or body.type not in lmap.block_kinds:+ return False+ census = _Census(lmap)+ stmts = _statements(body)+ if stmts and stmts[-1].type in lmap.return_kinds:+ stmts = stmts[:-1]+ if not all(_flat(s, census, top=True) for s in stmts):+ return False+ writes = census.writes+ owned = census.call_roots <= census.bound | set(params)+ return owned and len(census.roots) == 1 and writes >= max(_MIN_WRITES, len(census.bound) + 1)+++def _statements(block: Node) -> list[Node]:+ """*block*'s statements, comments and a leading docstring left out."""+ out = [c for c in block.named_children if not is_comment(c)]+ if len(out) == 1 and out[0].type == "statement_list":+ # Go wraps a block's statements in one list.+ return _statements(out[0])+ return out[1:] if out and is_string_stmt(out[0]) else out+++def _flat(stmt: Node, census: _Census, *, top: bool = False) -> bool:+ lmap = census.lmap+ kind = stmt.type+ if kind in _EMPTY_KINDS:+ return True+ if kind in lmap.function_kinds:+ # A local helper (``def add(label, value)``): calls to it are the writes.+ return top and census.bind([_find_function_entry_name(stmt, lmap)])+ if kind in lmap.block_kinds:+ return all(_flat(s, census) for s in _statements(stmt))+ if kind in lmap.if_kinds or kind in _ELSE_KINDS:+ return _flat_branches(stmt, census)+ if kind in lmap.try_kinds or kind in lmap.catch_kinds or kind == _FINALLY:+ return _flat_try(stmt, census)+ if kind in lmap.loop_kinds:+ return _flat_loop(stmt, census)+ if kind in lmap.local_decl_kinds:+ return _flat_decl(stmt, census)+ return _flat_expression(stmt, census)+++def _flat_try(stmt: Node, census: _Census) -> bool:+ # Only the clauses' blocks: a handler's exception type is no statement.+ lmap = census.lmap+ parts = lmap.block_kinds | lmap.catch_kinds | _ELSE_KINDS | {_FINALLY}+ return all(_flat(c, census) for c in stmt.named_children if c.type in parts)+++def _flat_loop(stmt: Node, census: _Census) -> bool:+ # One row per element; a loop inside it walks a structure.+ loop_body = stmt.child_by_field_name("body")+ if census.in_loop or loop_body is None:+ return False+ census.in_loop = True+ flat = _flat(loop_body, census)+ census.in_loop = False+ return flat+++def _flat_decl(stmt: Node, census: _Census) -> bool:+ lmap = census.lmap+ if _holds_callback(stmt, lmap):+ return False+ # Go's ``s := v`` is its own target; a TS or Java declaration holds declarators.+ holders = [stmt] if binding_target(stmt, lmap) is not None else stmt.named_children+ targets = [t for c in holders if (t := binding_target(c, lmap)) is not None]+ return census.bind([n for t in targets for n in bound_names(t)])+++def _flat_branches(stmt: Node, census: _Census) -> bool:+ """Every arm of an ``if`` chain is flat, or only returns."""+ condition = stmt.child_by_field_name("condition")+ arms = [c for c in stmt.named_children if c != condition and not is_comment(c)]+ return all(_guard_exit(arm, census.lmap) or _flat(arm, census) for arm in arms)+++def _guard_exit(arm: Node, lmap: LanguageNodeMap) -> bool:+ exits = lmap.return_kinds | lmap.raise_kinds+ if arm.type in exits:+ return True+ stmts = _statements(arm) if arm.type in lmap.block_kinds else []+ return len(stmts) == 1 and stmts[0].type in exits+++def _expression_of(stmt: Node, lmap: LanguageNodeMap) -> Node | None:+ """The one expression a statement holds; Go's assignment is its own statement."""+ if stmt.type in lmap.assignment_kinds:+ return stmt+ if stmt.type != _EXPR_STMT and stmt.type not in lmap.expr_stmt_kinds:+ return None+ return stmt.named_children[0] if stmt.named_child_count == 1 else None+++def _flat_expression(stmt: Node, census: _Census) -> bool:+ """A write to the census's one name, or a local bound to a value."""+ lmap = census.lmap+ expr = _expression_of(stmt, lmap)+ if expr is None or _holds_callback(stmt, lmap):+ return False+ target = binding_target(expr, lmap)+ if target is not None and _unwrap(target).type in _NAME_TARGETS:+ return census.bind(bound_names(target))+ written = target if target is not None else _written(expr, lmap)+ root = _root(written) if written is not None else None+ if root is None:+ return False+ census.roots.add(root)+ if target is None and expr.type in lmap.call_kinds:+ census.call_roots.add(root)+ census.writes += 1+ return True+++def _holds_callback(stmt: Node, lmap: LanguageNodeMap) -> bool:+ """Whether a function or lambda sits in *stmt*: its body is logic the+ statement only registers (``useEffect(() => ...)``, ``cmd.action(...)``)."""+ # A walk of one statement, and only flagged functions are judged.+ kinds = lmap.function_kinds | lmap.lambda_kinds+ stack = list(stmt.named_children)+ while stack:+ node = stack.pop()+ if node.type in kinds:+ return True+ stack.extend(node.named_children)+ return False+++def _written(expr: Node, lmap: LanguageNodeMap) -> Node | None:+ """What a statement-position call or ``delete`` writes through."""+ if expr.type in lmap.call_kinds:+ return _field(expr, _CALLEE_FIELDS)+ if expr.type == "unary_expression" and expr.children and expr.children[0].type == "delete":+ return expr.child_by_field_name("argument")+ return None+++def _field(node: Node, fields: tuple[str, ...]) -> Node | None:+ return next((c for f in fields if (c := node.child_by_field_name(f)) is not None), None)+++def _unwrap(node: Node) -> Node:+ """Go's one-element ``expression_list`` target, as its element."""+ if node.type == "expression_list" and node.named_child_count == 1:+ return node.named_children[0]+ return node+++def _root(node: Node) -> str | None:+ """The plain name an access chain starts from; ``None`` for a call result."""+ for _ in range(64):+ node = _unwrap(node)+ if node.type == "identifier":+ return node.text.decode("utf-8", "replace") if node.text else None+ nxt = _field(node, _ACCESS_FIELDS)+ if nxt is None or node.type in _CALL_KINDS:+ return None+ node = nxt+ return None+++__all__ = ["declarative_flat"]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 3b5b8d380..7c5402e8b 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@@ -33,7 +33,9 @@ A JSX function component whose decision points sit mostly in its markup(conditional spreads, ``&&`` and ternaries in attributes or children, templateternaries, all under a ``jsx_*`` node) is not offered one: that branching is prop plumbing, and a helperwould only move it. CCN is left alone because it feeds the calibrated defect-score; the gate is on eligibility.+score; the gate is on eligibility. Nor is a flat record builder+(:mod:`.declarative`): a function filling one value field by field behind+independent guards, which a helper would split in two without simplifying.The candidate spans + IN/OUT come from ``dataflow.find_extractions``; thismodule only matches each analysed function to the biomarker finding that flags@@ -113,7 +115,8 @@ from ..effort import effort_bucketfrom ..perf.dialects import PERF_DIALECTSfrom ..scoring import severity_deductionfrom . import render-from .helper_naming import ScopeNames, helper_name, out_value_name+from .declarative import declarative_flat+from .helper_naming import ScopeNames, helper_names, out_value_namefrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, register@@ -182,6 +185,11 @@ class ExtractMethodDetector(RefactoringDetector):continueif jsx_plumbing_dominates(analysis.fn_node, lmap):continue+ if analysis.fn_node is not None and declarative_flat(+ analysis.fn_node, lmap, {p.name for p in analysis.def_use.params}+ ):+ _mark_refused(matched, "declarative_flat")+ continuemarkers = {getattr(f, "biomarker_type", "") for f in matched}fn_node = analysis.fn_nodereceiver = dialect.receiver(fn_node, lmap) if dialect and fn_node else None@@ -200,9 +208,9 @@ class ExtractMethodDetector(RefactoringDetector):impact, share, source = self._impact_for(analysis, best, matched)name = render.private_name(ctx.language,- names.claim(+ names.claim_first(analysis,- helper_name(analysis, best, lmap, ctx.language, names.imports(fn_node)),+ helper_names(analysis, best, lmap, ctx.language, names.imports(fn_node)),),)async_fields = _async_fields(analysis, best, lmap, ctx.language)@@ -331,6 +339,18 @@ class ExtractMethodDetector(RefactoringDetector):return "medium"+#: The finding detail naming why a flagged function got no Extract Method plan.+#: Stored with the finding, so refusals are counted from the index.+REFUSED_DETAIL = "extract_method_refused"+++def _mark_refused(findings: list[Any], reason: str) -> None:+ for f in findings:+ details = getattr(f, "details", None)+ if isinstance(details, dict):+ details[REFUSED_DETAIL] = reason++def recovered_share(biomarker: str, analysis: FunctionAnalysis, extraction: Extraction) -> float:@@ -394,7 +414,8 @@ def _staged_fields(stages = []for x, reimports in zip(staged.stages, staged.imports, strict=True):name = render.private_name(- language, names.claim(analysis, helper_name(analysis, x, lmap, language, imports))+ language,+ names.claim_first(analysis, helper_names(analysis, x, lmap, language, imports)),)carried = [p for p in x.params if p in context]own = replace(x, params=tuple(p for p in x.params if p not in context))diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.pyindex a57626b46..3d7b6f413 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py@@ -5,13 +5,15 @@ comment over it (the author's own name for the block), and the span's singleOUT value as ``compute_<out>``. An OUT name describes a value, not an action,so it is never given to a span that acts outside itself (``dataflow.effects``);nor is a banner that opens with a value verb (``_VALUE_VERBS``). Whatever the-source, a name a symbol in the helper's scope already uses is dropped. ``None``-is the honest answer when nothing anchors a name, and every surface asks the-reader to name the helper then.+source, a name a symbol in the helper's scope already uses is dropped. Without+any of them, or when each is taken, the helper is named for its host function+and the span's subject (:mod:`.span_subject`), so every plan carries a name to+edit rather than a blank."""from __future__ import annotations+from collections.abc import Iterable, Iteratorfrom typing import TYPE_CHECKING, Anyfrom ..complexity.ast_utils import _find_function_entry_name@@ -26,6 +28,7 @@ from ..dataflow.effects import ()from ..dataflow.span import enclosing_with, section_heads, span_statementsfrom .naming import banner_words, join_identifier, label_words, split_words+from .span_subject import host_words, subjectsif TYPE_CHECKING:from ..complexity.languages import LanguageNodeMap@@ -115,6 +118,36 @@ def helper_name(return None if effects else out_value_name(analysis, extraction, language)+def helper_names(+ analysis: FunctionAnalysis,+ extraction: Extraction,+ lmap: LanguageNodeMap,+ language: str | None,+ modules: frozenset[str] = frozenset(),+) -> Iterator[str]:+ """Starting names, best first: :func:`helper_name`, then the host function+ qualified by each subject of the span (``render_card_directive``). Lazy, so+ the subjects are read only when the anchored name is missing or taken."""+ anchored = helper_name(analysis, extraction, lmap, language, modules)+ if anchored:+ yield anchored+ stmts = span_statements(analysis.fn_node, extraction.start_line, extraction.end_line, lmap)+ host = host_words(analysis.name) or ["handle"]+ for subject in subjects(stmts, extraction.returns, lmap):+ # ``render_card`` about ``card`` is ``render_card``: the host's own name.+ rest = subject[_overlap(host, subject) :]+ if rest:+ yield join_identifier([*host, *rest], _convention(language))+ # A span with no subject (it only logs, say) is still a block of the host.+ yield join_identifier([*host, "block"], _convention(language))+++def _overlap(host: list[str], subject: list[str]) -> int:+ """How many of *subject*'s first words repeat the tail of *host*."""+ top = min(len(host), len(subject))+ return next((n for n in range(top, 0, -1) if host[-n:] == subject[:n]), 0)++def _anchored_words(stmts: list[Any], lmap: LanguageNodeMap) -> list[str]:"""The words of the label or banner naming the span, ``[]`` without one.@@ -188,6 +221,11 @@ class ScopeNames:taken.add(key)return name+ def claim_first(self, analysis: FunctionAnalysis, names: Iterable[str]) -> str | None:+ """The first of *names* free in the helper's scope, claimed; ``None``+ when every one is taken."""+ return next((name for name in names if self.claim(analysis, name)), None)+def _scope_names(self, scope: Any) -> set[str]:names = {_key(n) for n in _defined_names(scope, self._lmap)}if scope.parent is None:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex e5bdb51c7..3e92fa79d 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -1273,6 +1273,32 @@ def apply_view(return spread+def listed_steps(steps: Sequence[Mapping[str, Any]], start: int, stop: int) -> list[dict[str, Any]]:+ """Steps ``[start, stop)`` of one opportunity as the plan list shows them.++ A step whose ``relocated_by`` is a ``split_file`` step works on code that+ split moves, so the split stands for it: the split's row lists its plan id+ as ``relocates`` and it gets no row of its own. Listed one by one, a single+ file filled the top of the list. Every other step keeps its row.+ """+ splits = {+ str(step.get("plan_id"))+ for step in steps+ if step.get("refactoring_type") == "split_file"+ }+ folded: dict[str, list[str]] = {}+ for step in steps:+ if step.get("relocated_by") in splits:+ folded.setdefault(str(step["relocated_by"]), []).append(str(step.get("plan_id")))+ rows: list[dict[str, Any]] = []+ for step in steps[start:stop]:+ if step.get("relocated_by") in splits:+ continue+ relocates = folded.get(str(step.get("plan_id")))+ rows.append({**step, "relocates": relocates} if relocates else dict(step))+ return rows++def _expand_scopes(path: str, reached: ReachedBy, expanded: list[str]) -> ReachedBy:"""*reached* with a conftest or test package it stopped at replaced by *expanded*.@@ -1329,6 +1355,7 @@ __all__ = ["detector_native_benefit","enrich_blast_radius","hub_files",+ "listed_steps","plan_types","priority_score","rehydrate_suggestion",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.py b/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.pynew file mode 100644index 000000000..96b55e972--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.py@@ -0,0 +1,185 @@+"""What an Extract Method span is about, read off its code, for the helper's name.++The last naming source, after a stage label, a banner and ``compute_<out>``+(:mod:`.helper_naming`): the host function's name qualified by the span's+subject, ``render_card`` + ``directive`` -> ``render_card_directive``. Both+halves are facts the plan holds, so the name says where the helper came from+and what it handles without guessing a verb for what it does.++The subject, first found: the span's single OUT value; the condition of the+``if`` arm or the target of the loop whose whole body the span is; then for+each of the span's statements in order, an ``if`` condition's subject (a string+key or compared literal, else the last name read), a loop's iterable, the+first name a statement binds, or a dropped call's name. Role words (``result``,+``self``) and one-letter names say nothing and are skipped.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING, Any++from ..dataflow.effects import binding_target, bound_names+from ..dataflow.span import body_holder, is_comment+from .naming import split_words++if TYPE_CHECKING:+ from ..complexity.languages import LanguageNodeMap++# Names that describe a role or a receiver, not what a block handles.+_ROLE_WORDS = frozenset(+ {"out", "result", "results", "value", "values", "ret", "tmp", "temp", "data", "item"}+ | {"self", "this", "cls", "none", "null", "undefined", "true", "false", "args", "kwargs"}+ # ``typeof x === "number"`` compares a type name, not the subject.+ | {"number", "string", "boolean", "object", "function", "bigint", "symbol"}+)+# A dropped call to one of these adds to something; the call's name says+# nothing about what (``out.append(...)``), so the next statement is read.+_GENERIC_CALLS = frozenset(+ {"append", "push", "add", "extend", "insert", "update", "set", "write", "print", "echo"}+ | {"log", "info", "debug", "warning", "warn", "error", "emit"}+)+# Calls that pass their subject through: ``card.get("owner")`` is about+# ``owner``, ``enumerate(groups)`` about ``groups``. ``_GENERIC_CALLS`` do too.+_PASS_THROUGH = frozenset(+ {"get", "items", "keys", "values", "enumerate", "sorted", "reversed", "list", "tuple"}+ | {"len", "iter", "getattr", "isinstance", "bool", "str", "int", "object", "array"}+)+_MEMBER_FIELDS = ("attribute", "property", "field")+_CALLEE_FIELDS = ("function", "callee")+_LOOP_SOURCE_FIELDS = ("right", "value", "iterable", "condition")+_PLAIN_NAME = re.compile(r"[A-Za-z_$][\w$]*")+_MAX_DEPTH = 8+++def host_words(name: str) -> list[str]:+ """The host function's name as words; ``[]`` for an anonymous or dotted one."""+ return split_words(name) if _PLAIN_NAME.fullmatch(name or "") else []+++def subjects(stmts: list[Any], returns: tuple[str, ...], lmap: LanguageNodeMap) -> list[list[str]]:+ """The span's subjects, best first, each as words, without repeats."""+ found: list[list[str]] = []+ if len(returns) == 1:+ found.append(_words(returns[0]))+ found.append(_enclosing_subject(stmts, lmap))+ code = [s for s in stmts if not is_comment(s)]+ for stmt in code:+ found.append(_statement_subject(stmt, lmap))+ if stmt.type in lmap.loop_kinds:+ # Over the host's own subject, the element is what the span handles.+ found.append(_expr_words(stmt.child_by_field_name("left"), 0))+ out: list[list[str]] = []+ for words in found:+ if words and words not in out:+ out.append(words)+ return out+++def _words(text: str) -> list[str]:+ words = split_words(text)+ if not words or "_".join(words) in _ROLE_WORDS or all(len(w) == 1 for w in words):+ return []+ return words+++def _enclosing_subject(stmts: list[Any], lmap: LanguageNodeMap) -> list[str]:+ """The subject of the ``if`` arm or loop whose whole body *stmts* is."""+ holder = body_holder(stmts)+ if holder is None:+ return []+ if holder.type in lmap.loop_kinds:+ return _expr_words(holder.child_by_field_name("left"), 0)+ return _expr_words(holder.child_by_field_name("condition"), 0)+++def _statement_subject(stmt: Any, lmap: LanguageNodeMap) -> list[str]:+ kind = stmt.type+ if kind in lmap.if_kinds:+ return _expr_words(stmt.child_by_field_name("condition"), 0)+ if kind in lmap.loop_kinds:+ return _expr_words(_child(stmt, _LOOP_SOURCE_FIELDS), 0)+ if kind in lmap.try_kinds or kind in lmap.with_kinds:+ return _wrapper_subject(stmt, lmap)+ expr = stmt.named_children[0] if stmt.named_child_count == 1 else stmt+ if expr.type in lmap.await_kinds | {"await_expression"} and expr.named_child_count == 1:+ expr = expr.named_children[0]+ bound = _bound_subject(expr, lmap)+ if bound is not None:+ return bound+ if expr.type not in lmap.call_kinds or _generic(_callee_words(expr, 0)):+ # ``out.append(...)`` says nothing about what is added: read on.+ return []+ return _expr_words(expr, 0)+++def _wrapper_subject(stmt: Any, lmap: LanguageNodeMap) -> list[str]:+ """A ``try`` or ``with`` is about what its body opens with."""+ body = stmt.child_by_field_name("body") or next(+ (c for c in stmt.named_children if c.type in lmap.block_kinds), None+ )+ first = next((c for c in body.named_children if not is_comment(c)), None) if body else None+ return _statement_subject(first, lmap) if first is not None else []+++def _bound_subject(expr: Any, lmap: LanguageNodeMap) -> list[str] | None:+ """``x = ...`` is about ``x``, ``state.registry = ...`` about ``registry``;+ ``None`` when *expr* binds nothing."""+ holders = [expr, *expr.named_children]+ target = next((t for h in holders if (t := binding_target(h, lmap)) is not None), None)+ if target is None:+ return None+ names = bound_names(target)+ return _words(names[0]) if names else _expr_words(target, 0)+++def _expr_words(node: Any, depth: int) -> list[str]:+ """The name an expression is about (module docstring)."""+ if node is None or depth > _MAX_DEPTH:+ return []+ if "string" in node.type:+ return _literal_words(node)+ if not node.named_children:+ text = (node.text or b"").decode("utf-8", "replace")+ return _words(text) if _PLAIN_NAME.fullmatch(text) else []+ if node.type in ("call", "call_expression"):+ return _call_words(node, depth)+ member = _child(node, _MEMBER_FIELDS)+ # A member names its field; otherwise a compared key, then the first operand.+ keys = [c for c in node.named_children if "string" in c.type]+ parts = [member] if member is not None else [*keys, *node.named_children]+ return next((w for c in parts if (w := _expr_words(c, depth + 1))), [])+++def _callee_words(call: Any, depth: int) -> list[str]:+ return _expr_words(_child(call, _CALLEE_FIELDS), depth + 1)+++def _generic(words: list[str]) -> bool:+ return "_".join(words) in _GENERIC_CALLS+++def _call_words(call: Any, depth: int) -> list[str]:+ """A call is about its name, or, when the name only passes a value on+ (``get``, ``len``, ``append``), its first argument, then its receiver."""+ name = _callee_words(call, depth)+ if name and not _generic(name) and "_".join(name) not in _PASS_THROUGH:+ return name+ callee = _child(call, _CALLEE_FIELDS)+ args = call.child_by_field_name("arguments")+ first = next((a for a in args.named_children if not is_comment(a)), None) if args else None+ receiver = _child(callee, ("object", "value")) if callee is not None else None+ return next((w for c in (first, receiver) if (w := _expr_words(c, depth + 1))), [])+++def _child(node: Any, fields: tuple[str, ...]) -> Any:+ return next((c for f in fields if (c := node.child_by_field_name(f)) is not None), None)+++def _literal_words(literal: Any) -> list[str]:+ """A string literal that is a plain key (``"recent_owner"``), as words."""+ text = (literal.text or b"").decode("utf-8", "replace").strip("'\"`")+ return _words(text) if _PLAIN_NAME.fullmatch(text) else []+++__all__ = ["host_words", "subjects"]diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py b/packages/server/src/repowise/server/mcp_server/tool_health/plans.pyindex 424ed3cbc..b8b2bee10 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py@@ -77,6 +77,9 @@ def _plan_row(step: dict[str, Any]) -> dict[str, Any]:row["classification"] = (step.get("applicability") or {}).get("classification")if step.get("relocated_by"):row["relocated_by"] = step["relocated_by"]+ if step.get("relocates"):+ # The plans after a split, which it stands for in the list.+ row["relocates"] = step["relocates"]return rowdiff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.pyindex 7e1a9dbed..931b9aec1 100644--- a/packages/server/src/repowise/server/services/refactoring_health.py+++ b/packages/server/src/repowise/server/services/refactoring_health.py@@ -27,6 +27,7 @@ from repowise.core.analysis.health.queue.counts import NOT_JUDGEDfrom repowise.core.analysis.health.queue_rules import keepfrom repowise.core.analysis.health.refactoring.recommendations import (PLAN_FILTERS,+ listed_steps,plan_types,stored_recommendation,)@@ -229,7 +230,9 @@ class RefactoringHealthService:A plan is a step of one opportunity, so the plan list is a view of thequeue: the same scope, filters and order, paged by plan. One narrow readof step counts places the page; only the opportunities it touches are- decoded.+ decoded. A split stands for the steps it relocates (``listed_steps``),+ so a page that folds some reads on until it holds ``limit`` rows;+ offsets and the total still count every plan."""filters, hidden = await self._scope(query, _filters(query))counts = await refactoring_step_counts(@@ -238,25 +241,36 @@ class RefactoringHealthService:**filters,order=query.resolved_order,)- window = _plan_window(counts, query.offset, query.limit)- rows = await refactoring_opportunities_by_id(- self._session, self._repository_id, list(window), status=query.status- )- # The window is in queue order; the read is not.- items = [- {**step, "opportunity_id": opportunity_id}- for opportunity_id, (start, stop) in window.items()- if opportunity_id in rows- for step in (detail_map(rows[opportunity_id]).get("steps") or [])[start:stop]- ]+ items: list[dict[str, Any]] = []+ touched: set[str] = set()+ position = query.offset+ # A page of splits standing for many plans costs a read or two more.+ while len(items) < query.limit:+ window = _plan_window(counts, position, query.limit - len(items))+ if not window:+ break+ before = position+ rows = await refactoring_opportunities_by_id(+ self._session, self._repository_id, list(window), status=query.status+ )+ # The window is in queue order; the read is not.+ for opportunity_id, (start, stop) in window.items():+ row = rows.get(opportunity_id)+ steps = (detail_map(row).get("steps") or []) if row is not None else []+ shown = listed_steps(steps, start, stop)+ items.extend({**step, "opportunity_id": opportunity_id} for step in shown)+ position += stop - start+ touched.add(opportunity_id)+ if position == before:+ breakreturn RefactoringPlanPage(items=items,total=sum(steps for _id, steps in counts),opportunities_total=len(counts),- next_offset=query.offset + sum(stop - start for start, stop in window.values()),+ next_offset=position,scope=query.scope,hidden=hidden,- counts=await self._counts(query, len(window)),+ counts=await self._counts(query, len(touched)),)async def _scope(diff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.pyindex b48735fdf..56f0293f4 100644--- a/tests/unit/health/test_extract_method_render.py+++ b/tests/unit/health/test_extract_method_render.py@@ -98,13 +98,14 @@ def _py_plan(call: str = "await self.flush(i)"):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+ # No label or banner: named for the host and the value it returns.+ assert plan["suggested_name"] == "_run_total"assert sym["signature_text"] == (- "async def <name>(self, items: list[int], limit: int) -> int:"+ "async def _run_total(self, items: list[int], limit: int) -> int:")assert plan["call_site"] == {"replace_span": plan["span"],- "new_text": "total = await self.<name>(items, limit)",+ "new_text": "total = await self._run_total(items, limit)",}# The receiver is not a parameter of a method.assert sym["params"] == [@@ -116,7 +117,7 @@ def test_python_plan_carries_an_awaited_method_header_and_call():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 plan["new_symbol"]["signature_text"].startswith("def _run_total(items: list[int]")assert "await" not in plan["call_site"]["new_text"]diff --git a/tests/unit/health/test_extract_method_stages.py b/tests/unit/health/test_extract_method_stages.pyindex 884ae256e..d3a720b61 100644--- a/tests/unit/health/test_extract_method_stages.py+++ b/tests/unit/health/test_extract_method_stages.py@@ -135,10 +135,10 @@ def test_persistence_shape_yields_a_staged_plan():def test_stage_names_come_from_timed_labels_and_banners():stages = _plans(_persist(sections=8, extend=()))["persist"].plan["stages"]- # A stage covering one section takes its label; one spanning two has none.+ # A stage covering one section takes its label; one spanning two is named+ # for the host and its subject.for stage in stages:- name = stage["suggested_name"]- assert name is None or name.startswith("_persist_part")+ assert stage["suggested_name"].startswith("_persist_")def test_shared_values_travel_on_a_parameter_object():diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.pyindex 1dcdab5f7..1a9987df4 100644--- a/tests/unit/health/test_recommendations.py+++ b/tests/unit/health/test_recommendations.py@@ -18,6 +18,7 @@ from repowise.core.analysis.health.refactoring.recommendations import (build_validation_plan,detector_native_benefit,hub_files,+ listed_steps,rehydrate_suggestion,steps_with_verify,stored_recommendation,@@ -890,3 +891,21 @@ def test_a_stored_row_without_usable_step_verify_serves_no_step_verify() -> Noneassert stored is not Nonesteps = stored.detail_dict()["plan"]["steps"]assert ["verify" in step for step in steps] == [True, False, False]+++def test_a_split_stands_for_the_steps_it_relocates():+ steps = [+ {"plan_id": "a", "refactoring_type": "break_cycle"},+ {"plan_id": "s", "refactoring_type": "split_file"},+ {"plan_id": "m1", "refactoring_type": "extract_method", "relocated_by": "s"},+ {"plan_id": "c", "refactoring_type": "extract_class", "relocated_by": "s"},+ {"plan_id": "m2", "refactoring_type": "extract_method", "relocated_by": "c"},+ ]+ rows = listed_steps(steps, 0, 2)+ assert [r["plan_id"] for r in rows] == ["a", "s"]+ assert rows[1]["relocates"] == ["m1", "c"]+ # A step another relocation moves keeps its row; the folded ones do not.+ assert [r["plan_id"] for r in listed_steps(steps, 2, 5)] == ["m2"]+ # Without a split, steps list one by one.+ plain = [{"plan_id": "x", "refactoring_type": "extract_method"}] * 2+ assert listed_steps(plain, 0, 2) == plaindiff --git a/tests/unit/health/test_refactoring_declarative.py b/tests/unit/health/test_refactoring_declarative.pynew file mode 100644index 000000000..4736e0229--- /dev/null+++ b/tests/unit/health/test_refactoring_declarative.py@@ -0,0 +1,286 @@+"""A flat record builder gets no Extract Method plan: its CCN comes from one+independent guard per field, and no helper makes either half simpler."""++from __future__ import annotations++import textwrap+from dataclasses import dataclass, field++import pytest++from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.dataflow import analyze_file+from repowise.core.analysis.health.refactoring import extract_method+from repowise.core.analysis.health.refactoring.declarative import declarative_flat+from repowise.core.analysis.health.refactoring.extract_method import (+ REFUSED_DETAIL,+ ExtractMethodDetector,+)+from repowise.core.analysis.health.refactoring.models import RefactoringContext+++@dataclass+class _Finding:+ biomarker_type: str+ function_name: str+ line_start: int+ health_impact: float+ details: dict = field(default_factory=dict)+++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)+ return res.functions+++def _flat(src: str, language: str = "python", ext: str = "py") -> bool:+ (fn,) = [f for f in _functions(language, ext, src) if f.name == "build"]+ return declarative_flat(fn.fn_node, get_language_map(language))+++# The configuration-summary shape: rows added behind one guard each.+_SUMMARY = """+def build(result, patterns, allow_fast, generate_docs=True):+ \"\"\"The summary rows.\"\"\"+ summary = []++ def add(label, value):+ summary.append((label, value))++ # Indexing+ add("Generate docs", "yes" if generate_docs else "no")+ add("Skip tests", "yes" if result["skip_tests"] else "no")+ if result["include_submodules"]:+ add("Include submodules", "yes")+ if allow_fast:+ add("Run mode", result["run_mode"])+ if patterns:+ if len(patterns) <= 5:+ add("Exclude", ", ".join(patterns))+ else:+ add("Exclude", "\\n".join(patterns))+ cap = result.get("max_file_pages")+ if cap:+ add("File pages", f"top {cap:,}")+ elif cap == 0:+ add("File pages", "all")+ if generate_docs:+ add("Concurrency", str(result["concurrency"]))+ if result.get("reasoning"):+ add("Reasoning", result["reasoning"])+ add("Embedder", result["embedder"])+ return summary+"""++# Query parameters set when given, then one request.+_QUERY_TS = """+export async function build(opts: Opts): Promise<Result> {+ const q = new URLSearchParams();+ if (opts.format) {+ q.set("format", opts.format);+ }+ if (typeof opts.limit === "number") {+ q.set("limit", String(opts.limit));+ }+ if (opts.selector?.trim()) {+ q.set("selector", opts.selector.trim());+ }+ if (opts.labels === true) q.set("labels", "1");+ return await fetchJson(`/snapshot?${q.toString()}`);+}+"""++# Fields copied when present, a guard clause first, one per-row loop.+_RECORD_TS = """+function build(raw: unknown, rows: Row[]): Settings | null {+ if (!raw) {+ return null;+ }+ const s: Settings = structuredClone(DEFAULTS);+ if (typeof raw.ttl === "string") {+ try {+ s.ttlMs = parseDuration(raw.ttl);+ } catch {+ // keep the default+ }+ }+ if (raw.tools) {+ s.tools = raw.tools;+ }+ if (raw.claims === null) {+ delete s.claims;+ }+ for (const row of rows) {+ s.items.push({ id: row.id, title: row.title ?? "untitled" });+ }+ return s;+}+"""+++ ("src", "language", "ext"),+ [(_SUMMARY, "python", "py"), (_QUERY_TS, "typescript", "ts"), (_RECORD_TS, "typescript", "ts")],+)+def test_a_flat_record_builder_is_declarative(src, language, ext):+ assert _flat(src, language, ext)+++ "change",+ [+ # A second name written is two jobs, not one record.+ (' add("Skip tests"', ' other.append(1)\n add("Skip tests"'),+ # A local the guards update is state, not a field.+ (' cap = result.get("max_file_pages")\n', ' cap = 1\n cap = result.get("x")\n'),+ # A loop inside a loop walks a structure.+ (+ " if allow_fast:\n",+ " for p in patterns:\n for q in p:\n add(p, q)\n if allow_fast:\n",+ ),+ # A call made for what it does, to anything else.+ (" if allow_fast:\n", " notify(result)\n if allow_fast:\n"),+ ],+)+def test_logic_beside_the_writes_is_not_declarative(change):+ old, new = change+ assert old in _SUMMARY+ assert not _flat(_SUMMARY.replace(old, new, 1))+++# Statement-level calls on module or imported names are steps, not fields:+# a function that logs or responds as it goes decomposes.+_LOGGING = """+def build(job, verbose):+ logger.info("start")+ if verbose:+ logger.debug("job %s", job.id)+ if job.retries:+ logger.warning("retrying %s", job.id)+ if job.failed:+ logger.error("failed %s", job.id)+ logger.info("done")+"""++_HANDLER_TS = """+function build(req: Request): void {+ if (!req.user) {+ res.status(401);+ }+ if (req.query.verbose) {+ res.set("x-verbose", "1");+ }+ if (req.query.format === "csv") {+ res.type("csv");+ }+ res.send(render(req));+}+"""+++ ("src", "language", "ext"), [(_LOGGING, "python", "py"), (_HANDLER_TS, "typescript", "ts")]+)+def test_calls_on_names_the_function_does_not_bind_are_not_a_builder(src, language, ext):+ assert not _flat(src, language, ext)+++_GO = """+package m++func build(cfg Config) Settings {+ s := Settings{}+ if cfg.Name != "" {+ s.Name = cfg.Name+ }+ if cfg.Port > 0 {+ s.Port = cfg.Port+ }+ if cfg.Debug {+ s.Debug = true+ }+ return s+}+"""++_GO_LOGIC = _GO.replace("s.Port = cfg.Port", "fmt.Println(cfg.Port)")++_JAVA = """+class M {+ Map<String, String> build(Config cfg) {+ Map<String, String> out = new HashMap<>();+ if (cfg.name != null) {+ out.put("name", cfg.name);+ }+ if (cfg.port > 0) {+ out.put("port", String.valueOf(cfg.port));+ }+ if (cfg.debug) {+ out.put("debug", "true");+ }+ return out;+ }+}+"""++_JAVA_LOGIC = _JAVA.replace('out.put("debug", "true");', 'System.out.println("debug");')+++ ("src", "language", "ext", "flat"),+ [+ (_GO, "go", "go", True),+ (_GO_LOGIC, "go", "go", False),+ (_JAVA, "java", "java", True),+ (_JAVA_LOGIC, "java", "java", False),+ ],+)+def test_go_and_java_builders(src, language, ext, flat):+ assert _GO_LOGIC != _GO and _JAVA_LOGIC != _JAVA+ assert _flat(src, language, ext) is flat+++def test_the_detector_refuses_a_flat_builder_and_keeps_a_real_split(monkeypatch):+ src = _SUMMARY + textwrap.dedent(+ """++ def process(records, threshold):+ results = []+ errors = 0+ for r in records:+ if r is None:+ errors += 1+ continue+ results.append(r)+ total = 0+ count = 0+ for v in results:+ if v > threshold:+ total += v+ count += 1+ else:+ total -= v+ average = total / count if count else 0+ return average, errors+ """+ )+ 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,+ )+ assert [s.target_symbol for s in ExtractMethodDetector().detect(ctx)] == ["process"]+ # The refusal is stored with the finding, so the index counts it.+ refused = {f.function_name: f.details.get(REFUSED_DETAIL) for f in ctx.findings}+ assert refused == {"build": "declarative_flat", "process": None}+ # The builder has a span the slicer would offer: the refusal is the shape.+ monkeypatch.setattr(extract_method, "declarative_flat", lambda *_: False)+ found = sorted(s.target_symbol for s in ExtractMethodDetector().detect(ctx))+ assert found == ["build", "process"]diff --git a/tests/unit/health/test_refactoring_extract_method_naming.py b/tests/unit/health/test_refactoring_extract_method_naming.pyindex ab33480de..99564c0dd 100644--- a/tests/unit/health/test_refactoring_extract_method_naming.py+++ b/tests/unit/health/test_refactoring_extract_method_naming.py@@ -1,6 +1,7 @@-"""Where an Extract Method helper's ``suggested_name`` comes from, and when it-has none: a ``timed()`` stage label, a banner comment, or ``compute_<out>`` for-an effect-free span, never a name a sibling in the helper's scope already uses.+"""Where an Extract Method helper's ``suggested_name`` comes from: a ``timed()``+stage label, a banner comment, ``compute_<out>`` for an effect-free span, else+the host function qualified by the span's subject; never a name a sibling in+the helper's scope already uses."""from __future__ import annotations@@ -13,7 +14,7 @@ import pytestfrom repowise.core.analysis.health.complexity.languages import get_language_mapfrom repowise.core.analysis.health.dataflow import Extraction, analyze_filefrom repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector-from repowise.core.analysis.health.refactoring.helper_naming import helper_name+from repowise.core.analysis.health.refactoring.helper_naming import helper_name, helper_namesfrom repowise.core.analysis.health.refactoring.models import RefactoringContext@@ -202,7 +203,8 @@ def test_a_timed_stage_label_names_the_helper():],)def test_a_span_with_outside_effects_is_not_named_compute(effect):- assert _name(_py(effect=effect)) is None+ # Named for its host and the value it produces, never ``compute_``.+ assert _name(_py(effect=effect)) == "process_average"@pytest.mark.parametrize(@@ -221,7 +223,7 @@ def test_reads_and_writes_to_what_the_span_owns_keep_the_name(effect):@pytest.mark.parametrize("verb", ["Compute", "Build", "Get", "Calculate"])def test_a_banner_promising_a_value_does_not_name_a_span_with_effects(verb):src = _py(head=f" # {verb} the totals\n", effect=" print(v)\n")- assert _name(src) is None+ assert _name(src) == "process_average"def test_a_banner_still_names_a_span_with_effects():@@ -258,7 +260,7 @@ def test_writing_through_self_is_an_effect():average = total / count if count else 0return average"""- assert _name(src) is None+ assert _name(src) == "process_average"# -- collisions with the helper's scope ------------------------------------------@@ -267,14 +269,14 @@ def test_writing_through_self_is_an_effect():@pytest.mark.parametrize("sibling", ["compute_average", "_compute_average"])def test_a_name_a_sibling_function_already_has_is_dropped(sibling):src = _py() + f"\n\ndef {sibling}(values):\n return sum(values) / len(values)\n"- assert _names(src) == [("process", None)]+ assert _names(src) == [("process", "process_average")]def test_two_plans_in_one_scope_do_not_share_a_name():second = textwrap.dedent(_py()).replace("def process(", "def process_again(")assert _names(_py() + "\n" + second) == [("process", "compute_average"),- ("process_again", None),+ ("process_again", "process_again_average"),]@@ -293,12 +295,12 @@ def test_a_method_does_not_collide_with_a_module_function():],)def test_module_assignments_and_imports_take_the_name(prefix):- assert _names(prefix + _py()) == [("process", None)]+ assert _names(prefix + _py()) == [("process", "process_average")]def test_the_host_functions_own_parameters_and_locals_take_the_name():src = _py().replace("(records, threshold)", "(records, threshold, compute_average=None)")- assert _names(src) == [("process", None)]+ assert _names(src) == [("process", "process_average")]# -- casing --------------------------------------------------------------------@@ -509,7 +511,7 @@ def test_go_exported_and_unexported_spellings_collide():src = _GO.replace(" // Sum values above threshold\n", "") + ("\nfunc ComputeAverage(xs []int) int {\n return 0\n}\n")- assert _names(src, "go", "go") == [("process", None)]+ assert _names(src, "go", "go") == [("process", "processAverage")]def test_a_one_line_jsdoc_is_a_banner_and_a_block_one_is_not():@@ -615,3 +617,86 @@ def test_rust_deref_writes_and_mut_borrows_are_effects(effect, acts):src = _RUST_EFFECT.replace("EFFECT", effect)name = _span_name("rust", "rs", src, 2, 10, ["values", "out", "c"], ["total"])assert (name is None) is acts+++# -- the host and the span's subject, when nothing else anchors a name ------------+++def _span_names(language, ext, src, start, end, returns=()):+ (fn,) = _functions(language, ext, src)+ first = fn.start_line - 1+ extraction = Extraction(first + start, first + end, (), tuple(returns), 8, 2, False)+ return list(helper_names(fn, extraction, get_language_map(language), language))+++def test_a_branch_body_is_named_for_the_branch_it_handles():+ src = """+ def render_plan(p, kind):+ out = []+ if kind == "break_cycle":+ out.append("cycle")+ elif kind == "split_file":+ groups = p.get("groups", [])+ out.append(len(groups))+ return out+ """+ assert _span_names("python", "py", src, 6, 7)[0] == "render_plan_split_file"+++def test_a_loop_is_named_for_what_it_walks_and_a_write_for_its_field():+ src = """+ def cmd_list(state, jobs):+ for job in jobs:+ print(job)+ state.registry = jobs+ """+ assert _span_names("python", "py", src, 2, 3) == ["cmd_list_jobs", "cmd_list_job", "cmd_list_block"]+ assert _span_names("python", "py", src, 4, 4) == ["cmd_list_registry", "cmd_list_block"]+++def test_a_subject_repeating_the_host_is_not_a_name():+ src = """+ def build_rows(rows, limit):+ for row in rows:+ print(row)+ """+ assert _span_names("python", "py", src, 2, 3) == ["build_rows_row", "build_rows_block"]+++def test_a_component_host_keeps_its_casing_and_starts_lowercase():+ src = """+ function OverviewPage(providers: Providers): number {+ const active = providers.active;+ track(active);+ const costPer1k = active ? active.cost : 0;+ return costPer1k;+ }+ """+ names = _span_names("typescript", "ts", src, 2, 4, ["costPer1k"])+ assert names[0] == "overviewPageCostPer1k"+++def test_a_camel_case_host_follows_the_files_convention():+ src = """+ def buildRows(rows, limit):+ for row in rows:+ print(row)+ """+ assert _span_names("python", "py", src, 2, 3) == ["build_rows_row", "build_rows_block"]+++def test_a_span_with_no_subject_is_a_block_of_its_host():+ src = """+ def report(job):+ logger.info("start")+ logger.info("done")+ """+ assert _span_names("python", "py", src, 2, 3) == ["report_block"]+ anonymous = """+ const run = function () {+ console.log("start");+ console.log("done");+ };+ """+ # An unnamed function expression has no host name to qualify.+ assert _span_names("typescript", "ts", anonymous, 2, 3) == ["handleBlock"]diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 0475b7238..3565bc733 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -221,7 +221,7 @@ async def _seed_plans(session, rid, plans):"target_symbol": p.get("target_symbol", "authenticate"),"line_start": 10,"line_end": 80,- "plan": {"groups": []},+ "plan": p.get("plan", {"groups": []}),"evidence": {},"impact_delta": p["impact_delta"],"effort_bucket": "S",@@ -1527,6 +1527,75 @@ async def test_refactoring_plans_follow_the_queue_in_queue_order(setup_mcp, healassert "plan" not in every[0] and "evidence" not in every[0]+async def test_a_split_stands_for_the_plans_it_relocates(setup_mcp, health_data, session):+ """The plans after a split work on code it moves: the split's row lists+ them as ``relocates`` and they take no rows, so one file cannot fill the+ list. Offsets and the total still count every plan."""+ from repowise.server.mcp_server import get_health++ await _seed_plans(+ session,+ health_data,+ [+ {+ "refactoring_type": "split_file",+ "file_path": "src/auth/service.py",+ "target_symbol": "service.py",+ "plan": {+ "groups": [+ {"suggested_file": "src/auth/tokens.py", "symbols": ["moved_0"]},+ {"suggested_file": "src/auth/login.py", "symbols": ["moved_1"]},+ ]+ },+ "source_biomarker": "large_file",+ "impact_delta": 9.0,+ }+ ]+ + [+ {+ "file_path": "src/auth/service.py",+ "target_symbol": f"moved_{i}",+ "source_biomarker": "complex_method",+ "impact_delta": 5.0,+ }+ for i in range(3)+ ]+ + [+ {+ "file_path": "src/utils/helpers.py",+ "target_symbol": f"other_{i}",+ "source_biomarker": "complex_method",+ "impact_delta": 0.1,+ }+ for i in range(2)+ ],+ )+ asked = {"include": ["refactoring"], "only": ["refactoring_plans"], "refactoring_scope": "all"}+ first = await get_health(**asked, limit=2)+ rows = first["refactoring_plans"]+ assert [r["refactoring_type"] for r in rows] == ["split_file", "extract_method"]+ assert len(rows[0]["relocates"]) == 3+ assert rows[1]["file_path"] == "src/utils/helpers.py"+ assert first["refactoring_plans_total"] == 6+ # The page covered the split, the three it stands for and one more plan.+ assert first["recovery"]["refactoring_plans"]["call"].endswith("cursor=5)")+ rest = (await get_health(**asked, limit=10, cursor=5))["refactoring_plans"]+ assert [r["target_symbol"] for r in rest] == ["other_1"]+ detail = await get_health(plan_id=rows[0]["relocates"][0])+ assert detail["plan"]["target_symbol"].startswith("moved_")+ # The REST plan list ranks plans one by one and folds nothing.+ from repowise.server.services.refactoring_health import (+ PlanListQuery,+ RefactoringHealthService,+ )++ ranked = await RefactoringHealthService(session, health_data, "default").ranked_plans(+ PlanListQuery()+ )+ assert {p["target_symbol"] for p in ranked["plans"]} >= {f"moved_{i}" for i in range(3)}++@pytest.mark.asyncioasync def test_refactoring_plans_honour_scope(setup_mcp, health_data, session):"""``refactoring_scope="all"`` lists the inventory; the default lists what