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(health): keep refactoring plans within one language and name their targets (#3277)
Raghav Chamadiya5b189be57ff9
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 9fa76b8b7..1a6d8be0e 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -271,7 +271,8 @@ Each low-scoring file can carry deterministic refactoring plans (Extract Method,Split File, Break Cycle, Performance Fix and others) with evidence, gain, effort andblast radius. `repowise health --refactoring-targets` prints the stored queue.Break Cycle is advisory: it is shown beside a file's steps, never as one, and-never in Fix first. See [REFACTORING.md](REFACTORING.md).+never in Fix first. A Split File or Extract Class plan with an unnamed group is+held the same way (`needs_design`). See [REFACTORING.md](REFACTORING.md).## Trends, coverage and badgesdiff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex fca58107f..d56694e1d 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -100,7 +100,10 @@ a file whose only plan is a cycle). The plan list's `structural_total` leavesBreak Cycle out, matching the opportunities; `by_type` still counts it.Names are never invented. A suggested helper or file name is `null` when nothing-in the code anchors one.+in the code anchors one. A Split File or Extract Class plan with an unnamed group+is held as `needs_design`, like a cycle: it is not a step and never reaches Fix+first. Code only moves within a language family, so Java, Kotlin and Scala are+separate. A callback is named after the call it is passed to.An empty list means no detector found work that clears its gates. It does not meanthe code needs no attention: check the findings indiff --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 e01a1d2a9..37d9a2bdf 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@@ -537,34 +537,50 @@ def _render_opportunities_md(opportunities: list[dict], plan_by_id: dict) -> Nondef _render_unattached_console(plans: list[dict]) -> None:"""Plans no opportunity claims.- A file whose only plans are demoted clones or advisory cycles publishes no- opportunity, so without this the CLI would print a smaller number than the- analyzer found and call it the total. They are listed as observations,- under their own heading, rather than folded back in as work.+ A file whose only plans are demoted clones, advisory cycles or splits+ with an unnamed group publishes no opportunity, so without this the CLI+ would print a smaller number than the analyzer found and call it the+ total. They are listed as observations, under their own heading, rather+ than folded back in as work."""if not plans:returnconsole.print(f"\n[bold]Unattached observations ({len(plans)})[/bold]")console.print(- "[dim]Duplication and import cycles, not ranked work: no file's "- "opportunity is built on them.[/dim]"+ "[dim]Duplication, import cycles and splits with unnamed groups, not "+ f"ranked work: no file's opportunity is built on them.{_design_note(plans)}[/dim]")for p in plans:- console.print(f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']})[/dim]")+ console.print(+ f"\n[cyan]{p['target_symbol']}[/cyan] [dim]({p['file_path']}){_design_tag(p)}[/dim]"+ )for line in _plan_detail_console(p):console.print(line)+def _design_note(plans: list[dict]) -> str:+ from repowise.core.analysis.health.refactoring_summary import needs_design++ held = sum(needs_design(p) for p in plans)+ return f" {held} need design: a group has no name yet." if held else ""+++def _design_tag(plan: dict) -> str:+ from repowise.core.analysis.health.refactoring_summary import needs_design++ return " needs design" if needs_design(plan) else ""++def _render_unattached_md(plans: list[dict]) -> None:if not plans:returnclick.echo("\n## Unattached observations\n")click.echo(- "Duplication and import cycles, not ranked work: no file's opportunity is "- "built on them.\n"+ "Duplication, import cycles and splits with unnamed groups, not ranked "+ f"work: no file's opportunity is built on them.{_design_note(plans)}\n")for p in plans:- click.echo(f"- **{p['target_symbol']}** ({p['file_path']})")+ click.echo(f"- **{p['target_symbol']}** ({p['file_path']}){_design_tag(p)}")for line in _plan_detail_md(p):click.echo(line)diff --git a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.pyindex 5f002b56c..7c41282ea 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py@@ -13,6 +13,7 @@ both ask the same question of a listed receiver.from __future__ import annotations+import refrom typing import TYPE_CHECKINGfrom .languages import LanguageNodeMap@@ -31,6 +32,13 @@ _DECLARATOR_NAME_KINDS = frozenset({"identifier", "field_identifier", "type_identifier", "qualified_identifier"})+# Longest callee path a callback's name carries. A longer chain keeps its+# trailing segments, which name the call the callback is handed to.+_MAX_CALLEE_PATH = 100+# A callee whose source text is already a dotted name (``ipcMain.handle``,+# ``this.on``) and is kept as written.+_PLAIN_PATH = re.compile(r"[\w$#]+(?:\.[\w$#]+)*")+def _pascal_unwrap_name(name: Node) -> Node:"""Pascal: unwrap ``genericDot`` (``TFoo.Bar``) / ``genericTpl`` (``Bar<T>``)@@ -161,9 +169,19 @@ def _find_call_callback_callee(node: Node) -> str | None:if call is None or call.type != "call_expression":return Nonecallee = call.child_by_field_name("function")- if callee is None or callee.text is None:+ if callee is None:return None- return " ".join(_node_text(callee).split())+ path = _node_text(callee)+ if not _PLAIN_PATH.fullmatch(path):+ # A chained callee (``z.object({...}).superRefine``) would carry every+ # argument in its text; its identifier path names the same call.+ path = ".".join(_identifier_chain(callee, lower=False))+ if len(path) > _MAX_CALLEE_PATH:+ # Start the kept tail at a segment boundary; one identifier longer than+ # the cap has none, so its own tail stands.+ tail = path[-_MAX_CALLEE_PATH:]+ path = tail.partition(".")[2] or tail+ return path or None_TEST_SUITE_CALLBACK_CALLEES = frozenset({"describe", "context", "suite"})@@ -346,20 +364,23 @@ def _count_parameters(fn_node: Node) -> int:return count-def _identifier_chain(node: Node) -> list[str]:- """Every identifier under *node*, lowercased, in document order.+def _identifier_chain(node: Node, *, lower: bool = True) -> list[str]:+ """Every identifier under *node*, lowercased unless *lower* is false, in+ document order.Order is load-bearing: the last entry is the name being called, the rest- the receiver path. Argument lists are never descended into.+ the receiver path. Argument lists and ``type_arguments`` (TypeScript,+ Java) are never descended into; C#'s ``type_argument_list`` still is."""names: list[str] = []stack: list[Node] = [node]while stack:cur = stack.pop()- if cur.type in ("argument_list", "arguments"):+ if cur.type in ("argument_list", "arguments", "type_arguments"):continueif cur.type.endswith(_IDENTIFIER_SUFFIX) and cur.text is not None:- names.append(cur.text.decode("utf-8", "replace").lower())+ text = cur.text.decode("utf-8", "replace")+ names.append(text.lower() if lower else text)stack.extend(reversed(cur.children))return namesdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py b/packages/core/src/repowise/core/analysis/health/complexity/test_case.pyindex d7d49af18..09595fb43 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/test_case.py@@ -46,7 +46,8 @@ if TYPE_CHECKING:from tree_sitter import Node#: Suffix ``ast_utils._find_function_entry_name`` gives a callback entry, as in-#: ``"it callback"``. The text before it is the callee, arguments included.+#: ``"it callback"``. The text before it is the callee's dotted path+#: (``it.each`` for ``it.each([...])``), arguments left out._CALLBACK_SUFFIX = " callback"_JAVA_MODIFIERS = "modifiers"@@ -142,9 +143,9 @@ def is_test_case(fn_node: Node, name: str, language: str) -> bool:if not dialect.callback_callees:return Falsecallee = lowered[: -len(_CALLBACK_SUFFIX)]- # ``it.each([1,2])`` carries its arguments in the entry name; the first- # dotted segment is the framework function in every form of it.- return callee.split(".", 1)[0].split("(", 1)[0] in dialect.callback_callees+ # The first dotted segment is the framework function in every form of+ # it (``it``, ``it.each``, ``it.skip``).+ return callee.split(".", 1)[0] in dialect.callback_calleesif dialect.name_prefixes and lowered.startswith(dialect.name_prefixes):return Trueif _matches_runner_prefix(name, dialect.runner_prefixes):diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex ba54a4377..a69fe2fd2 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -114,7 +114,11 @@ log = structlog.get_logger(__name__)# or ``python_files`` leaves it out (``core/test_selection.py``). Its# ``is_test`` flag flips, and the biomarkers and ``has_test_file`` now read that# stored flag instead of re-classifying the path, so such a module joins the-# production scores and findings.+# production scores and findings. A callback passed to a chained or curried+# call (``it.each([...])(...)``, ``z.object({...}).superRefine(...)``) is named+# by the call's dotted path without its arguments, so findings and perf hits+# inside one get a new ``function_name`` and a new public id; triage stored on+# the old id no longer attaches.## v38: Split File's co-change edge reads per-function commit# sets (the 50 newest distinct commits of each function, stored ondiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.pyindex 9dc885f18..6796cb08b 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py@@ -48,6 +48,7 @@ from typing import Anyfrom ....code_origin import is_migration_path, is_vendored_or_generated_pathfrom ....test_paths import is_test_related_pathfrom ..duplication.detector import clone_ranges, union_line_count+from .language_family import same_language_familyfrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, effort_bucket, register@@ -431,10 +432,15 @@ class ExtractHelperDetector(RefactoringDetector):# then coalesce the overlapping windows the clone detector emits for one# physical block into a single site per region (without merging, the# same import/parse block reads as "5 sites" when it is really one).- # Clones are detected within a language, so every occurrence in a block- # shares ``ctx.language`` — which the ambiguous ``spec/`` rule needs.+ # The clone index hashes token shapes across every language, so a site+ # in another language family is dropped too: no shared helper can serve+ # it. What is left shares ``ctx.language``'s family, which the+ # ambiguous ``spec/`` rule needs.kept = [- o for o in block.occurrences if not _is_skippable_occurrence(o[0], ctx.language)+ o+ for o in block.occurrences+ if same_language_family(ctx.file_path, o[0])+ and not _is_skippable_occurrence(o[0], ctx.language)]occurrences = [odiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/language_family.py b/packages/core/src/repowise/core/analysis/health/refactoring/language_family.pynew file mode 100644index 000000000..84adc1cdf--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/language_family.py@@ -0,0 +1,54 @@+"""Whether code can move between two files: they must share a language family.++A plan that relocates code (a method moved to another class, a helper shared by+clone sites) only makes sense when the source and the destination compile+together. The call graph and the clone index can both pair files across+languages (a Swift method resolved onto a Kotlin class of the same name, an+import list that tokenizes like one in Python), so the detectors ask here+before naming a destination.++A family is the set of languages one build mixes freely: TypeScript and+JavaScript (and the single-file components that host them), C and C++ with+their headers and Objective-C, C# with Razor. Every other language is its own+family; that includes the JVM languages, so a Java, Kotlin or Scala move into+another of the three is dropped, the conservative side of real interop. A file+whose extension maps to no language is its own family too, keyed by its+extension, or by its whole name when it has none (a ``Makefile`` never pairs+with a ``Dockerfile``), so two unknown files never pair by accident.+"""++from __future__ import annotations++from pathlib import PurePosixPath++from ....ingestion.models import EXTENSION_TO_LANGUAGE++_FAMILY: dict[str, str] = {+ "typescript": "js",+ "javascript": "js",+ "vue": "js",+ "svelte": "js",+ "c": "c",+ "cpp": "c",+ "objectivec": "c",+ "csharp": "dotnet",+ "razor": "dotnet",+}+++def language_family(path: str) -> str:+ """The language family *path* belongs to, read off its extension."""+ name = PurePosixPath(path.replace("\\", "/")).name.lower()+ suffix = PurePosixPath(name).suffix+ language = EXTENSION_TO_LANGUAGE.get(suffix)+ if language is None:+ return f"ext:{suffix or name}"+ return _FAMILY.get(language, language)+++def same_language_family(path_a: str, path_b: str) -> bool:+ """Whether code written in *path_a* can move into *path_b*."""+ return language_family(path_a) == language_family(path_b)+++__all__ = ["language_family", "same_language_family"]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.pyindex b2c6759c9..6e2fe467a 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py@@ -50,7 +50,9 @@ name such as ``toString``) cannot move either, since the type it overrides foris the reason it exists. Building the target through a static factory(``OperationResult.Ok()``, any target member returning the target type) countsas instantiating it, and an interface, an exception type, a ``*Util``/``*Helper``-class or a C# ``static class`` is never a home for instance behaviour. The+class or a C# ``static class`` is never a home for instance behaviour, and+neither is a class in another language family (a Swift call the graph resolved+onto a Kotlin class of the same name). Theother ``partial`` fragments of the method's own class are its own class."""@@ -63,6 +65,7 @@ from repowise.core.analysis.dead_code.contract_methods import is_contract_methodfrom repowise.core.analysis.execution_graph import is_reliable_call_edgefrom ....test_paths import is_test_related_path+from .language_family import same_language_familyfrom .models import RefactoringContext, RefactoringSuggestionfrom .registry import RefactoringDetector, effort_bucket, register@@ -251,11 +254,17 @@ def _never_a_target(graph: Any, class_id: str) -> bool:return any(n.endswith(_NON_TARGET_SUFFIXES) for n in names)-def _is_target(graph: Any, class_id: str, accessed: set[str], home: set[str]) -> bool:+def _is_target(+ graph: Any, class_id: str, accessed: set[str], home: set[str], home_file: str+) -> bool:"""A foreign class the method could move to: not its own class or an- ancestor (*home*), not a class it builds, not a non-target kind."""+ ancestor (*home*), not a class it builds, not a non-target kind, and in a+ file *home_file*'s code can move into (a call resolved across languages+ names a class the method cannot live in)."""+ target_file = (_node(graph, class_id) or {}).get("file_path") or class_id.rpartition("::")[0]return (class_id not in home+ and same_language_family(home_file, target_file)and not _builds(graph, class_id, accessed)and not _never_a_target(graph, class_id))@@ -415,7 +424,7 @@ class MoveMethodDetector(RefactoringDetector):foreign = [(c, m)for c, m in accessed_by_class.items()- if _is_target(graph, c, m, own_and_inherited)+ if _is_target(graph, c, m, own_and_inherited, ctx.file_path)]if not foreign:return Nonediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.pyindex 1e99d40bc..e8df027d3 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py@@ -33,6 +33,11 @@ none of the cycles it named were worth cutting. It rides along as evidence thesame way, so it is never a numbered step, never leads, and never reaches Fixfirst; the plan stays in the plan inventory.+**An unnamed group is a design question, not a step.** A ``split_file`` or+``extract_class`` plan with a group it cannot name says what to separate but+not what the result is (``needs_design``). It rides along as evidence the same+way, until the group has a name.+**A finding is recovered once.** A step names the findings its own targetanswers: the source biomarker's findings whose span it covers, and for anamed finding only the one on the same symbol. Two steps answering one@@ -52,7 +57,7 @@ from dataclasses import dataclassfrom typing import Anyfrom ...finding_registry import excluded_types-from ..refactoring_summary import ADVISORY_TYPES+from ..refactoring_summary import ADVISORY_TYPES, needs_designfrom ..rows import fieldfrom .extract_helper import ACTIVE_CO_CHANGEfrom .identity import REFACTORING_MODEL_VERSION, assign_public_ids, stable_id@@ -242,7 +247,7 @@ def is_standalone_clone(suggestion: RefactoringSuggestion) -> bool:def _is_step(suggestion: RefactoringSuggestion) -> bool:- if suggestion.refactoring_type in ADVISORY_TYPES:+ if suggestion.refactoring_type in ADVISORY_TYPES or needs_design(suggestion):return Falseif suggestion.refactoring_type == "extract_helper":return is_standalone_clone(suggestion)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.pyindex cb71211a6..8bd794807 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py@@ -22,6 +22,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Literal+from ..refactoring_summary import groups_named, needs_designfrom .models import RefactoringSuggestionfrom .recommendations import affected_files, blast_size@@ -38,7 +39,7 @@ JUDGMENT_REASONS = ("changes_symbol_home","detector_confidence_below_high","inverts_imports_across_files",- "no_named_target",+ "needs_design","reshapes_class_surface","rewrites_dependent_imports","unclassified_refactoring_type",@@ -75,19 +76,6 @@ def _int_or_none(value: Any) -> int | None:return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None-def _named_groups(plan: dict[str, Any]) -> bool | None:- """Whether every proposed group names the file it lands in.-- ``None`` when the plan proposes no groups at all: absence of groups is not- evidence that the naming succeeded, and R1 made an unnameable group emit- ``null`` rather than invent a filename.- """- groups = [group for group in (plan.get("groups") or []) if isinstance(group, dict)]- if not groups:- return None- return all(group.get("suggested_file") for group in groups)--# Which facts each refactoring type can even have. A key absent here is not# unknown, it is meaningless: asking whether an Extract Method needs a# re-export shim has no answer, and reporting one as ``None`` would read as a@@ -97,7 +85,7 @@ _BASE_FACT_KEYS = ("affected_file_count", "cross_file", "blast_size", "confidenc_TYPE_FACT_KEYS: dict[str, tuple[str, ...]] = {"extract_method": ("local_scope",),"split_file": ("shim_required", "groups_named", "dependents", "framework_registration"),- "extract_class": ("dependents", "framework_registration"),+ "extract_class": ("groups_named", "dependents", "framework_registration"),"move_method": ("callers", "framework_registration"),"break_cycle": ("framework_registration",),"extract_helper": ("co_change_count",),@@ -126,7 +114,7 @@ def step_facts(suggestion: RefactoringSuggestion) -> tuple[dict[str, Any], tuple"callers": _int_or_none(blast.get("callers")),"co_change_count": _int_or_none(evidence.get("co_change_count")),"shim_required": plan.get("shim_required") if "shim_required" in plan else None,- "groups_named": _named_groups(plan),+ "groups_named": groups_named(plan),# No graph is in scope here, so whether a framework registers the symbols# a step moves is never known. It is reported rather than omitted because# it is the fact that keeps every symbol-moving step a judgment call.@@ -175,8 +163,6 @@ def _split_file_reasons(_suggestion: RefactoringSuggestion, facts: dict[str, Any"""if facts["shim_required"] is not False:return ["rewrites_dependent_imports", "changes_symbol_home"]- if facts["groups_named"] is not True:- return ["no_named_target"]return ["build_constraints_unknown"]@@ -200,6 +186,8 @@ def classify_step(suggestion: RefactoringSuggestion) -> StepApplicability:reasons = _split_file_reasons(suggestion, facts)else:reasons = list(_JUDGMENT_BY_TYPE.get(kind, ("unclassified_refactoring_type",)))+ if needs_design(suggestion):+ reasons.insert(0, "needs_design")# ``all`` over nothing is True, so a future branch that returned no reason# would promote silently. Mechanical has to be positively argued.mechanical = bool(reasons) and all(reason in MECHANICAL_REASONS for reason in reasons)@@ -217,5 +205,6 @@ __all__ = ["Applicability","StepApplicability","classify_step",+ "needs_design","step_facts",]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring_summary.py b/packages/core/src/repowise/core/analysis/health/refactoring_summary.pyindex 27c0e05c9..219907d21 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring_summary.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring_summary.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom collections.abc import Iterablefrom typing import Any-from repowise.core.analysis.health.rows import field+from repowise.core.analysis.health.rows import field, json_field#: Plans an opportunity carries as evidence, never as a step: a cycle names#: edges to cut but not which symbols cross them.@@ -20,6 +20,11 @@ ADVISORY_TYPES = frozenset({"break_cycle"})#: lead; ``by_type`` still counts them.STRUCTURAL_TYPES = frozenset({"split_file", "extract_class", "move_method"})+#: The types whose plan is a set of groups to create. With a group unnamed, the+#: plan says what to separate but not what the result is: a design decision for+#: a person, held out of every opportunity's steps (``needs_design``).+GROUPING_TYPES = frozenset({"split_file", "extract_class"})+#: A plan recovers health at or above this ``impact_delta``.HEALTH_RECOVERY_MIN = 0.1@@ -28,6 +33,31 @@ HEALTH_RECOVERY_MIN = 0.1NEGLIGIBLE_HEALTH_BELOW = 0.5+def groups_named(plan: dict[str, Any]) -> bool | None:+ """Whether every proposed group is named: the file a split group lands in,+ or the class an extracted group becomes.++ ``None`` when the plan proposes no groups at all: absence of groups is not+ evidence that the naming succeeded, and an unnameable group is emitted as+ ``null`` rather than given an invented name.+ """+ groups = [group for group in (plan.get("groups") or []) if isinstance(group, dict)]+ if not groups:+ return None+ return all(group.get("suggested_file") or group.get("name") for group in groups)+++def needs_design(row: Any) -> bool:+ """Whether *row* (a suggestion, ORM row or dict) is a grouping plan with a+ group it does not name."""+ if field(row, "refactoring_type") not in GROUPING_TYPES:+ return False+ plan = field(row, "plan", None)+ if not isinstance(plan, dict):+ plan = json_field(row, "plan_json", {})+ return groups_named(plan if isinstance(plan, dict) else {}) is not True++def summarize_plans(plans: Iterable[Any]) -> dict[str, Any]:"""Chip counts for *plans*, each with ``refactoring_type``, ``file_path``,``effort_bucket`` and ``impact_delta``. Shaped like ``RefactoringSummary``."""@@ -47,6 +77,9 @@ def summarize_plans(plans: Iterable[Any]) -> dict[str, Any]:"structural_total": sum(field(plan, "refactoring_type") in STRUCTURAL_TYPES for plan in plans),+ # Structural plans no opportunity takes as a step, so the structural+ # chip and the opportunities reconcile.+ "design_total": sum(needs_design(plan) for plan in plans),"performance_total": by_type.get("performance_fix", 0),"small_effort_total": sum(field(plan, "effort_bucket") == "S" for plan in plans),"health_recovery_total": sum(impact >= HEALTH_RECOVERY_MIN for impact in impacts),@@ -57,8 +90,11 @@ def summarize_plans(plans: Iterable[Any]) -> dict[str, Any]:__all__ = ["ADVISORY_TYPES",+ "GROUPING_TYPES","HEALTH_RECOVERY_MIN","NEGLIGIBLE_HEALTH_BELOW","STRUCTURAL_TYPES",+ "groups_named",+ "needs_design","summarize_plans",]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.pyindex 7b0dfa30b..9ce67e650 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py@@ -222,10 +222,12 @@ def _summary_payload(statuses: dict[str, str],lead_details: dict[str, Any] | None,plan_ids: set[str],+ design_plan_ids: set[str],) -> dict[str, Any]:"""The rollup. ``plans_total`` is the plan inventory behind it, split intosteps, evidence and plans in no opportunity, so the plan and opportunity- counts reconcile."""+ counts reconcile. ``design_total`` names the grouping plans held out of the+ steps for an unnamed group; they sit in the evidence or unattached share."""from ....analysis.health.refactoring.opportunity import claimed_plan_idsby_type: dict[str, int] = {}@@ -257,6 +259,7 @@ def _summary_payload("plans_total": len(plan_ids),"evidence_total": sum(len(item.evidence) for item in opportunities),"unattached_plans_total": len(plan_ids - claimed_plan_ids(opportunities)),+ "design_total": len(design_plan_ids & plan_ids),"by_lead_type": by_type,"by_effort": by_effort,"by_confidence": by_confidence,@@ -292,6 +295,7 @@ async def finalize_refactoring_opportunities(opportunity_status,)from ....analysis.health.refactoring.recommendations import hydrate_recommendations+ from ....analysis.health.refactoring_summary import needs_designplan_rows = list((@@ -433,6 +437,7 @@ async def finalize_refactoring_opportunities(statuses=statuses,lead_details=lead_details,plan_ids={row.public_id for row in live_plans if row.public_id},+ design_plan_ids={row.public_id for row in live_plans if needs_design(row)},analyzed_commit=analyzed_commit,)return sum(1 for state in statuses.values() if state != "resolved")@@ -522,12 +527,14 @@ async def _write_summary(statuses: dict[str, str],lead_details: dict[str, Any] | None,plan_ids: set[str],+ design_plan_ids: set[str],analyzed_commit: str | None,) -> None:from ....analysis.health.refactoring.identity import REFACTORING_MODEL_VERSIONpayload = json.dumps(- _summary_payload(opportunities, statuses, lead_details, plan_ids), separators=(",", ":")+ _summary_payload(opportunities, statuses, lead_details, plan_ids, design_plan_ids),+ separators=(",", ":"),)row = await session.get(RefactoringSummary, repository_id)if row is None:diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex 1119f8b20..28fb1fb2f 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -110,6 +110,7 @@ class RefactoringSummary(BaseModel):by_type: list[RefactoringTypeCount]files_total: int | None = Nonestructural_total: int | None = None+ design_total: int | None = Noneperformance_total: int | None = Nonesmall_effort_total: int | None = Nonehealth_recovery_total: int | None = Nonediff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 6c144cefc..be4885974 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2804,6 +2804,7 @@ export interface RefactoringSummary {by_type: RefactoringTypeCount[];files_total?: number | null;structural_total?: number | null;+ design_total?: number | null;performance_total?: number | null;small_effort_total?: number | null;health_recovery_total?: number | null;diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex 61c453447..b5d913977 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -83,6 +83,9 @@ export interface RefactoringSummary {/** Additive Phase 4 aggregates; absent on older servers. */files_total?: number;structural_total?: number;+ /** Split File / Extract Class plans with an unnamed group (`needs_design`):+ * counted in `structural_total`, never a step. */+ design_total?: number;performance_total?: number;small_effort_total?: number;health_recovery_total?: number;@@ -349,10 +352,13 @@ export interface RefactoringRollupAvailable {judgment_steps_total: number;/** The plan inventory: steps + evidence + unattached. Absent on older indexes. */plans_total?: number;- /** Plans carried as evidence (demoted clones, advisory cycles), not steps. */+ /** Plans carried as evidence (demoted clones, advisory cycles, unnamed groups), not steps. */evidence_total?: number;/** Plans no opportunity carries; listed only in the plan inventory. */unattached_plans_total?: number;+ /** Plans held out of the steps for an unnamed group (`needs_design`); part of+ * the evidence and unattached shares. */+ design_total?: number;by_lead_type: Record<string, number>;by_effort: Record<string, number>;by_confidence: Record<string, number>;diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonindex 6ba0a071d..ea393f61f 100644--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -1,74 +1,5 @@{- "gopkg": [- {- "addresses_primary_problem": null,- "affected_files": [- "inventory.go"- ],- "confidence": "high",- "effort_bucket": "L",- "evidence": [],- "file_path": "inventory.go",- "judgment_steps": 1,- "lead_biomarker": null,- "lead_refactoring_type": "split_file",- "mechanical_steps": 0,- "opportunity_id": "refop4_5a97fa33cd4c4ffc9740",- "rank_factors": {- "benefit": 1.6931,- "cost": 3.0,- "mechanical_share": 0.0,- "primary_problem": 0.0,- "risk": 0.0- },- "rank_score": 0.4233,- "recoverable_health": 0.0,- "refactoring_model_version": 4,- "step_count": 1,- "steps": [- {- "applicability": {- "classification": "judgment",- "facts": {- "affected_file_count": 1,- "blast_size": 0,- "confidence": "high",- "cross_file": false,- "dependents": 0,- "framework_registration": null,- "groups_named": false,- "shim_required": false- },- "reasons": [- "no_named_target"- ],- "unknowns": [- "framework_registration"- ]- },- "confidence": "high",- "effort_bucket": "L",- "file_path": "inventory.go",- "impact_delta": 0.0,- "plan_id": "refac4_396717806264bd16aab8",- "refactoring_type": "split_file",- "relocated_by": null,- "source_biomarker": "",- "target_symbol": "inventory.go -> 2 files"- }- ],- "why_ranked": [- {- "factor": "cost",- "value": 3.0- },- {- "factor": "benefit",- "value": 1.6931- }- ]- }- ],+ "gopkg": [],"orm": [],"tsapp": [{diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.pyindex 997e1d3a7..7268f58ce 100644--- a/tests/unit/cli/test_refactoring_targets_render.py+++ b/tests/unit/cli/test_refactoring_targets_render.py@@ -250,3 +250,29 @@ def test_an_idiomatic_cycle_is_marked_optional_in_the_detail(capsys):_render_refactoring_targets([], [], [cycle], fmt="md")text = capsys.readouterr().outassert "(same directory, idiomatic; optional)" in text+++def test_an_unattached_split_with_an_unnamed_group_says_it_needs_design(capsys):+ split = RefactoringSuggestion(+ refactoring_type="split_file",+ file_path="pkg/big.py",+ target_symbol="big.py -> 2 files",+ line_start=None,+ line_end=None,+ plan={+ "groups": [+ {"name": "walk", "symbols": ["walk"], "suggested_file": "pkg/walk.py"},+ {"name": None, "symbols": ["a", "b"], "suggested_file": None},+ ],+ "shim_required": True,+ },+ evidence={"group_count": 2},+ impact_delta=0.0,+ effort_bucket="L",+ blast_radius={"dependent_count": 0},+ confidence="high",+ )+ _render_refactoring_targets([], [], [split], fmt="md")+ text = capsys.readouterr().out+ assert "1 need design: a group has no name yet." in text+ assert "- **big.py -> 2 files** (pkg/big.py) needs design" in textdiff --git a/tests/unit/health/test_assertion_free_test.py b/tests/unit/health/test_assertion_free_test.pyindex dd7574f9d..7cd70d997 100644--- a/tests/unit/health/test_assertion_free_test.py+++ b/tests/unit/health/test_assertion_free_test.py@@ -127,9 +127,9 @@ def test_js_suite_and_setup_callbacks_are_not_test_cases() -> None:assert "localHelper" not in casesassert "it callback" in casesassert "test callback" in cases- # ``it.each([1,2])`` carries its arguments in the entry name; the first- # dotted segment is still the framework function.- assert "it.each([1, 2]) callback" in cases+ # ``it.each([1,2])`` is named by its dotted path, arguments left out; the+ # first segment is still the framework function.+ assert "it.each callback" in casesdef test_a_language_with_no_row_classifies_nothing() -> None:diff --git a/tests/unit/health/test_ast_callee_names.py b/tests/unit/health/test_ast_callee_names.pynew file mode 100644index 000000000..108c6f33e--- /dev/null+++ b/tests/unit/health/test_ast_callee_names.py@@ -0,0 +1,57 @@+"""Callee names and receiver sets for generic calls, after type arguments are+skipped by ``_identifier_chain``.++The mock and assertion passes read these. Pinned so the effect of skipping a+type-argument list is explicit: TS ``type_arguments`` under a curried callee+used to supply the called name (``factory.make<Bar>()(x)`` read as ``bar``).+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.complexity.ast_utils import _callee_names++_CALL_KINDS = ("invocation_expression", "call_expression", "method_invocation")+++def _calls(language: str, source: str) -> dict[str, tuple[str, set[str]] | None]:+ try:+ from tree_sitter import Parser++ from repowise.core.ingestion.parser import _get_language++ tree = Parser(_get_language(language)).parse(source.encode())+ except Exception:+ pytest.skip(f"no {language} grammar on this build")+ out: dict[str, tuple[str, set[str]] | None] = {}+ stack = [tree.root_node]+ while stack:+ node = stack.pop()+ if node.type in _CALL_KINDS:+ out[node.text.decode()] = _callee_names(node)+ stack.extend(node.children)+ return out+++def test_a_curried_typescript_generic_reads_its_callee_not_its_type_argument() -> None:+ calls = _calls("typescript", "const g = factory.make<Bar>()(x); const m = vi.mocked<Foo>(dep);")+ assert calls["factory.make<Bar>()(x)"] == ("make", {"factory"})+ assert calls["factory.make<Bar>()"] == ("make", {"factory"})+ assert calls["vi.mocked<Foo>(dep)"] == ("mocked", {"vi"})+++def test_a_java_explicit_type_argument_never_joins_the_receivers() -> None:+ calls = _calls("java", "class T { void m() { Foo f = Mockito.<Foo>mock(Foo.class); } }")+ assert calls["Mockito.<Foo>mock(Foo.class)"] == ("mock", {"mockito"})+++def test_csharp_generic_calls_are_unchanged() -> None:+ """C#'s grammar names the list ``type_argument_list``, which is not+ skipped, so the type argument still reads as the called name. Recorded as+ the current behaviour, not endorsed."""+ calls = _calls(+ "csharp", "class T { void M() { var s = Substitute.For<IFoo>(); Arg.Any<MockFoo>(); } }"+ )+ assert calls["Substitute.For<IFoo>()"] == ("ifoo", {"substitute", "for"})+ assert calls["Arg.Any<MockFoo>()"] == ("mockfoo", {"arg", "any"})diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex d35857ab7..65797d2a3 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -282,6 +282,36 @@ test.describe("routes", () => {assert "beforeEach callback" in names+def test_a_chained_callee_names_its_callback_by_identifier_path():+ """A zod schema's ``superRefine`` callback was named after the whole+ ``z.object({...})`` expression, a name thousands of characters long."""+ _require_language("typescript")+ fields = ", ".join(f"field{i}: z.string().optional()" for i in range(40))+ source = f"""+export const Schema = z+ .object({{ {fields} }})+ .strict()+ .superRefine((value, ctx) => {{+ if (value.field1 && !value.field2) {{+ ctx.addIssue({{ code: "custom", message: "field2" }});+ }}+ }});++it.each([{{ name: "a", x: 1 }}, {{ name: "b", x: 2 }}])("case $name", ({{ x }}) => {{+ expect(x).toBeGreaterThan(0);+}});++makeHandler<Entry[]>(config)((entry) => {{+ return entry.id;+}});+""".encode()+ names = [fn.name for fn in walk_file("/tmp/schema.ts", "typescript", source).functions]+ assert "z.object.strict.superRefine callback" in names+ assert "it.each callback" in names+ assert "makeHandler callback" in names+ assert all(len(name) <= 120 and "(" not in name for name in names)++def test_rust_flat_match_complexity():"""A flat match (all arms are simple expressions) should count as 1 CCNpoint for the match itself; individual arms should NOT add CCN."""diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.pyindex b325c82ab..bd540ca94 100644--- a/tests/unit/health/test_refactoring_extract_helper.py+++ b/tests/unit/health/test_refactoring_extract_helper.py@@ -284,6 +284,27 @@ def test_test_file_dropped_but_real_sites_kept():assert files == ["pkg/a.py", "pkg/b.py"]+def test_a_site_in_another_language_is_dropped():+ # The clone index hashes token shapes across languages: an export list in+ # TypeScript paired with one in Python. No helper serves both.+ clones = [+ _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55),+ _pair("pkg/a.py", "ui/c.ts", 10, 25, 5, 20),+ ]+ sugs = [+ s+ for s in detect_refactorings(_ctx("pkg/a.py", clones))+ if s.refactoring_type == "extract_helper"+ ]+ assert [o["file"] for o in sugs[0].plan["occurrences"]] == ["pkg/a.py", "pkg/b.py"]+ only_cross = [_pair("pkg/a.py", "ui/c.ts", 10, 25, 5, 20)]+ assert [+ s+ for s in detect_refactorings(_ctx("pkg/a.py", only_cross))+ if s.refactoring_type == "extract_helper"+ ] == []++def test_generated_migration_occurrences_dropped():# Migration boilerplate duplicates heavily but is never refactored — a# clone confined to migration files yields no suggestion.diff --git a/tests/unit/health/test_refactoring_language_family.py b/tests/unit/health/test_refactoring_language_family.pynew file mode 100644index 000000000..85d8e71c5--- /dev/null+++ b/tests/unit/health/test_refactoring_language_family.py@@ -0,0 +1,38 @@+"""Which files code can move between: one language family."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.refactoring.language_family import same_language_family+++ ("a", "b"),+ [+ ("ui/App.tsx", "ui/querier.ts"),+ ("ui/App.vue", "ui/util.js"),+ ("src/net.c", "include/net.h"),+ ("src/view.mm", "src/model.cpp"),+ ("Pages/Index.razor", "Pages/Index.razor.cs"),+ ("pkg/a.py", "pkg/b.pyi"),+ ],+)+def test_one_build_mixes_these(a: str, b: str) -> None:+ assert same_language_family(a, b)+++ ("a", "b"),+ [+ ("ios/NodeAppModel.swift", "android/OpenClawCanvasA2UIAction.kt"),+ ("pkg/a.py", "ui/c.ts"),+ # JVM interop is real, but a move across it is left to a person.+ ("src/A.java", "src/B.kt"),+ ("src/A.scala", "src/B.java"),+ # No extension: the whole name is the key, so two unknowns never pair.+ ("Makefile", "Dockerfile"),+ ],+)+def test_code_never_moves_across_these(a: str, b: str) -> None:+ assert not same_language_family(a, b)diff --git a/tests/unit/health/test_refactoring_move_method.py b/tests/unit/health/test_refactoring_move_method.pyindex 5dc1be7c8..255233447 100644--- a/tests/unit/health/test_refactoring_move_method.py+++ b/tests/unit/health/test_refactoring_move_method.py@@ -480,3 +480,30 @@ def test_other_partial_fragments_of_the_own_class_are_home():"C.cs", "T.cs", edge_type="imports", imported_names=["C"], hint_source="partial_class")assert _detect_in(g, "C.cs", "csharp") == []+++def test_a_class_in_another_language_is_never_a_move_target():+ """The call graph resolved a Swift method onto a Kotlin class of the same+ name (openclaw NodeAppModel.swift -> OpenClawCanvasA2UIAction.kt)."""+ g = _envy_graph_in("swift", "swift")+ nx.relabel_nodes(+ g,+ {n: n.replace("T.swift", "T.kt") for n in list(g) if n.startswith("T.swift")},+ copy=False,+ )+ for node in ("T.kt::T", "T.kt::T.Alpha", "T.kt::T.Beta", "T.kt::T.Gamma"):+ g.nodes[node].update(file_path="T.kt", language="kotlin")+ assert _detect_in(g, "C.swift", "swift") == []+++def test_a_target_in_the_same_language_family_still_moves():+ g = _envy_graph_in("tsx", "typescript")+ nx.relabel_nodes(+ g,+ {n: n.replace("T.tsx", "T.js") for n in list(g) if n.startswith("T.tsx")},+ copy=False,+ )+ for node in ("T.js::T", "T.js::T.Alpha", "T.js::T.Beta", "T.js::T.Gamma"):+ g.nodes[node].update(file_path="T.js", language="javascript")+ out = _detect_in(g, "C.tsx", "typescript")+ assert [s.plan["to_file"] for s in out] == ["T.js"]diff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.pyindex 497cee75b..480ac4051 100644--- a/tests/unit/health/test_refactoring_opportunity.py+++ b/tests/unit/health/test_refactoring_opportunity.py@@ -163,32 +163,88 @@ def test_a_file_with_only_a_cycle_publishes_nothing() -> None:assert compose_opportunities([cycle()]) == []+def unnamed_split() -> RefactoringSuggestion:+ """ours ``augment_cmd/_shared.py -> 4 files``: a group with no name."""+ row = split()+ groups = [dict(group) for group in row.plan["groups"]]+ groups[1].update(name=None, suggested_file=None)+ return plan(+ "split_file",+ row.target_symbol,+ plan={**row.plan, "groups": groups},+ evidence=row.evidence,+ impact_delta=0.0,+ blast_radius=row.blast_radius,+ source_biomarker="",+ )+++def test_a_split_with_an_unnamed_group_is_evidence_not_a_step() -> None:+ opportunity = compose_opportunities([unnamed_split(), plan("extract_method")])[0]+ assert [step.refactoring_type for step in opportunity.steps] == ["extract_method"]+ assert [item.refactoring_type for item in opportunity.evidence] == ["split_file"]+ assert compose_opportunities([unnamed_split()]) == []+++def test_an_extract_class_with_unnamed_groups_is_evidence_not_a_step() -> None:+ groups = [{"name": None, "methods": ["a", "b"], "fields": ["x", "y"]}] * 2+ unnamed = plan("extract_class", "Orders", plan={"groups": groups})+ assert compose_opportunities([unnamed]) == []+++def test_a_split_whose_groups_are_all_named_stays_a_step() -> None:+ """ours ``refactoring_targets.py -> 3 files`` (``groups_named`` true)."""+ opportunity = compose_opportunities([split()])[0]+ assert [step.refactoring_type for step in opportunity.steps] == ["split_file"]+ assert "needs_design" not in opportunity.steps[0].applicability.reasons++@pytest.mark.usefixtures("dry_violation_shown")def test_plan_inventory_is_steps_plus_evidence_plus_unattached() -> None:"""The rollup's plan counts reconcile with the opportunities they fold into."""from repowise.core.analysis.health.refactoring.identity import assign_public_idsfrom repowise.core.analysis.health.refactoring.opportunity import claimed_plan_ids+ from repowise.core.analysis.health.refactoring_summary import needs_design, summarize_plansfrom repowise.core.persistence.crud.analysis.refactoring_opportunities import (_summary_payload,)+ groups = [{"name": None, "methods": ["a", "b"], "fields": ["x", "y"]}] * 2rows = [plan("extract_method"),cycle(),clone(intra=True, co_change=0),cycle(file_path="svc/only_cycle.py"),+ unnamed_split(),+ plan("extract_class", "Billing", file_path="svc/billing.py", plan={"groups": groups}),+ split(file_path="svc/named.py"),]opportunities = compose_opportunities(rows)- plan_ids = set(assign_public_ids(rows))- summary = _summary_payload(opportunities, {}, None, plan_ids)+ ids = assign_public_ids(rows)+ plan_ids = set(ids)+ design_ids = {pid for pid, row in zip(ids, rows, strict=True) if needs_design(row)}+ summary = _summary_payload(opportunities, {}, None, plan_ids, design_ids)steps = sum(item.step_count for item in opportunities)- assert summary["evidence_total"] == 2 # the cycle and the clone in orders.py- assert summary["unattached_plans_total"] == 1 # the cycle-only file- assert summary["plans_total"] == 4+ # orders.py: the cycle, the clone and the unnamed split+ assert summary["evidence_total"] == 3+ # the cycle-only file and the unnamed class+ assert summary["unattached_plans_total"] == 2+ assert summary["plans_total"] == 7assert summary["plans_total"] == (steps + summary["evidence_total"] + summary["unattached_plans_total"])- assert len(plan_ids - claimed_plan_ids(opportunities)) == 1+ assert len(plan_ids - claimed_plan_ids(opportunities)) == 2+ # Every held-out grouping plan is in the evidence or unattached share, and the+ # structural chip less the held-out ones is the structural steps.+ assert summary["design_total"] == 2+ chips = summarize_plans(rows)+ structural_steps = sum(+ step.refactoring_type in ("split_file", "extract_class", "move_method")+ for item in opportunities+ for step in item.steps+ )+ assert chips["design_total"] == summary["design_total"]+ assert chips["structural_total"] - chips["design_total"] == structural_steps == 1# --------------------------------------------------------------------------diff --git a/tests/unit/health/test_refactoring_preconditions.py b/tests/unit/health/test_refactoring_preconditions.pyindex 2956aa753..94258d243 100644--- a/tests/unit/health/test_refactoring_preconditions.py+++ b/tests/unit/health/test_refactoring_preconditions.py@@ -9,6 +9,7 @@ from repowise.core.analysis.health.refactoring.preconditions import (JUDGMENT_REASONS,MECHANICAL_REASONS,classify_step,+ needs_design,step_facts,)@@ -110,12 +111,43 @@ def test_a_split_that_needs_a_shim_is_a_judgment_call() -> None:assert "rewrites_dependent_imports" in applicability.reasons-def test_a_split_nobody_can_name_a_target_for_is_not_mechanical() -> None:+def test_a_split_nobody_can_name_a_target_for_needs_design() -> None:plan = dict(go_split().plan)- plan["groups"] = [{"symbols": ["Stock"], "suggested_file": None}]- applicability = classify_step(go_split(plan=plan))+ plan["groups"] = [{"symbols": ["Stock"], "name": None, "suggested_file": None}]+ row = go_split(plan=plan)+ applicability = classify_step(row)assert applicability.classification == "judgment"- assert applicability.reasons == ("no_named_target",)+ assert applicability.reasons == ("needs_design", "build_constraints_unknown")+ assert needs_design(row)+ assert not needs_design(go_split())+++def test_a_shimmed_split_with_an_unnamed_group_needs_design() -> None:+ """ours ``ast_utils.py -> 5 files``: ``groups_named`` false."""+ plan = {+ "shim_required": True,+ "groups": [+ {"name": "walk", "symbols": ["walk"], "suggested_file": "pkg/walk.py"},+ {"name": None, "symbols": ["a", "b"], "suggested_file": None},+ ],+ }+ applicability = classify_step(step("split_file", plan=plan))+ assert applicability.reasons[0] == "needs_design"+ assert applicability.facts["groups_named"] is False+++def test_an_extract_class_with_unnamed_groups_needs_design() -> None:+ groups = [{"name": None, "methods": ["a", "b"], "fields": ["x", "y"]}] * 2+ row = step("extract_class", plan={"groups": groups})+ assert needs_design(row)+ assert classify_step(row).reasons[0] == "needs_design"+ named = [dict(group, name=f"Part{i}") for i, group in enumerate(groups)]+ assert not needs_design(step("extract_class", plan={"groups": named}))+++def test_only_grouping_plans_can_need_design() -> None:+ for kind in ("extract_method", "extract_helper", "move_method", "break_cycle"):+ assert not needs_design(step(kind))@pytest.mark.parametrize(diff --git a/tests/unit/health/test_refactoring_tree_corpus.py b/tests/unit/health/test_refactoring_tree_corpus.pyindex 70069ac33..b73990b88 100644--- a/tests/unit/health/test_refactoring_tree_corpus.py+++ b/tests/unit/health/test_refactoring_tree_corpus.py@@ -13,6 +13,7 @@ from .refactoring_tree_fixture import (MANIFEST,TREES_DIR,UNCOVERED,+ analyze_tree,archetype_roots,compose_tree,load_golden,@@ -121,20 +122,26 @@ def test_a_split_offered_on_go_is_classified_not_dropped() -> None:Two facts refuse the promotion independently: this fixture's groups cannotbe named, and no split can prove the absence of a file-scoped build- constraint. See ``UNCOVERED``.+ constraint. See ``UNCOVERED``. The unnamed group also holds it out of the+ steps: it stays a plan, never an instruction."""+ from repowise.core.analysis.health.refactoring.preconditions import classify_step++ report = analyze_tree(TREES_DIR / "gopkg")splits = [- step- for opportunity in compose_tree(TREES_DIR / "gopkg")- for step in opportunity["steps"]- if step["refactoring_type"] == "split_file"+ row+ for row in getattr(report, "refactoring_suggestions", None) or []+ if row.refactoring_type == "split_file"]if not splits:pytest.skip("no Go grammar on this build")- for step in splits:- assert step["applicability"]["facts"]["shim_required"] is False- assert step["applicability"]["classification"] == "judgment"- assert step["applicability"]["reasons"] == ["no_named_target"]+ for row in splits:+ applicability = classify_step(row)+ assert applicability.facts["shim_required"] is False+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("needs_design", "build_constraints_unknown")+ for opportunity in compose_tree(TREES_DIR / "gopkg"):+ assert "split_file" not in [step["refactoring_type"] for step in opportunity["steps"]]def test_composition_is_deterministic_across_runs() -> None:diff --git a/tests/unit/server/test_refactoring_summary_golden.py b/tests/unit/server/test_refactoring_summary_golden.pyindex 6ade35417..7d9d9e629 100644--- a/tests/unit/server/test_refactoring_summary_golden.py+++ b/tests/unit/server/test_refactoring_summary_golden.py@@ -45,6 +45,7 @@ def test_summary_counts_and_threshold_edges() -> None:],"files_total": 5,"structural_total": 3, # break_cycle is advisory: counted in by_type only+ "design_total": 2, # the split and the class name no group: never a step"performance_total": 1,"small_effort_total": 3,"health_recovery_total": 6,@@ -59,6 +60,7 @@ def test_summary_of_nothing() -> None:"by_type": [],"files_total": 0,"structural_total": 0,+ "design_total": 0,"performance_total": 0,"small_effort_total": 0,"health_recovery_total": 0,