Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(refactoring): stop three plan fields from reporting constants as measurements (#1374)

Raghav Chamadiya829062eedb08
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 4037e8b01..e5bbe2d40 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -60,11 +60,11 @@ web).
|-------|---------|
| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` \| `extract_method` |
| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |
-| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns`. |
+| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns` + `suggested_name`. |
| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. |
| `impact_delta` | The health score the refactoring would recover (the deduction of the marker it answers); `0` for the graph-native types that answer no marker. |
| `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. |
-| `blast_radius` | What else must move: the callers, co-change partners, and importing files. |
+| `blast_radius` | What else must move: the callers, co-change partners, and importing files. Extract Method carries `{"scope": "local"}` instead — extraction adds a private helper and changes no signature, so nothing outside the file moves and there is no count to make. |
| `confidence` | `low` \| `medium` \| `high` (drives the `min_confidence` surface gate). |
| `source_biomarker` | The finding this answers (e.g. `low_cohesion`, `god_class`, `dry_violation`). |
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index b09a10bee..ea6e2f366 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
@@ -179,7 +179,10 @@ def _render_extract_helper_plans_console(plans: list[dict]) -> None:
ev = p["evidence"]
occ = p["plan"].get("occurrences", [])
site = p["plan"].get("suggested_site", {}) or {}
- where = site.get("module") or site.get("directory") or "a shared module"
+ # ``directory`` first: it is the only namespace new plans carry, and on
+ # plans stored before that it was the correct one anyway (``module`` held
+ # a community label naming a directory the occurrences were not in).
+ where = site.get("directory") or site.get("module") or "a shared module"
co = ev.get("co_change_count", 0)
console.print(
f"\n[cyan]{ev.get('duplicated_lines')} duplicated lines[/cyan] across "
@@ -200,7 +203,10 @@ def _render_extract_helper_plans_md(plans: list[dict]) -> None:
ev = p["evidence"]
occ = p["plan"].get("occurrences", [])
site = p["plan"].get("suggested_site", {}) or {}
- where = site.get("module") or site.get("directory") or "a shared module"
+ # ``directory`` first: it is the only namespace new plans carry, and on
+ # plans stored before that it was the correct one anyway (``module`` held
+ # a community label naming a directory the occurrences were not in).
+ where = site.get("directory") or site.get("module") or "a shared module"
click.echo(
f"- **{ev.get('duplicated_lines')} duplicated lines** across "
f"{len(occ)} sites — extract a helper near `{where}`:"
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
index f897f55c1..8fdced152 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
@@ -42,6 +42,7 @@ from typing import Any
from ....test_paths import is_test_related_path
from .models import RefactoringContext, RefactoringSuggestion
+from .naming import identifier_slug
from .registry import RefactoringDetector, effort_bucket, register
# The biomarker this detector answers — the recovered impact is read off it.
@@ -230,7 +231,7 @@ class ExtractHelperDetector(RefactoringDetector):
impact = self._impact_for_block(anchor_region, impact_lookup)
is_intra = len(occ_files) == 1
- suggested_site = self._suggested_site(ctx, occ_files)
+ suggested_site = self._suggested_site(occ_files)
snippet, snippet_start, snippet_truncated = self._snippet_for(ctx, anchor_region)
plan = {
"occurrences": [{"file": f, "line_start": s, "line_end": e} for f, s, e in occurrences],
@@ -270,24 +271,42 @@ class ExtractHelperDetector(RefactoringDetector):
source_biomarker=_SOURCE_BIOMARKER,
)
- def _suggested_site(
- self, ctx: RefactoringContext, occ_files: list[str]
- ) -> dict[str, str | None]:
- """Where the shared helper should live: the community centroid of the
- occurrences (the module most of them belong to), with the shared
- directory as a fallback when no community labels exist."""
- module = None
- if ctx.module_map:
- counts: dict[str, int] = {}
- for f in occ_files:
- mod = ctx.module_map.get(f)
- if mod:
- counts[mod] = counts.get(mod, 0) + 1
- if counts:
- # Centroid = most-shared module; ties broken lexicographically
- # so the site is deterministic.
- module = min(counts, key=lambda m: (-counts[m], m))
- return {"module": module, "directory": _common_directory(occ_files)}
+ @staticmethod
+ def _suggested_site(occ_files: list[str]) -> dict[str, str | None]:
+ """Where the shared helper should live: the deepest directory every
+ occurrence shares.
+
+ One namespace, and it is the filesystem — because the field's job is to
+ name a place a file can go. This used to lead with a graph *community*
+ label under the key ``module``, alongside the directory, and that was
+ wrong twice over:
+
+ - **A label is not a location.** Censused over the 963 stored
+ ``extract_helper`` plans on this repo's own index, 905 carried a
+ label and **905 of 905 named a directory that no occurrence lives
+ in** — ``module: "ui"`` for a block shared by ``packages/api-client``,
+ ``packages/types`` and ``packages/ui``. Acting on it files shared code
+ into a package two thirds of its callers are not in.
+ - **The namespace depended on the writer.** ``module_map`` is populated
+ only by the full-index path; the incremental, re-score and
+ ``repowise health`` paths leave it empty, so the same clone got
+ ``"ui"`` or ``None`` depending on which pass last wrote the row. That
+ is exactly the defect the ``module`` column was fixed for; the
+ refactoring payload had kept it.
+
+ The honest answer is sometimes a shallow one — a block shared across
+ three packages has no home better than ``packages`` — and saying so is
+ the point. A nicer-reading label that names the wrong package is worse
+ advice, not better.
+
+ Deliberately *not* ``package_roots.module_for``, the shipped definition
+ of the ``module`` column: that answers "which bucket does this file
+ report under", and for placement the shared directory is strictly more
+ specific (for a block confined to ``.../providers/llm`` it is that
+ directory, where ``module_for`` would say ``packages/core``). Package
+ attribution is a rollup axis; this is a destination.
+ """
+ return {"directory": _common_directory(occ_files)}
@staticmethod
def _snippet_for(
@@ -384,28 +403,20 @@ def _suggested_name(suggested_site: dict[str, str | None]) -> str:
Precision-first: without semantics we cannot name the block for what it
*does*, so we anchor the name to where the helper will live (the shared
- module or directory leaf) and suffix ``_helper``. It is an editable
- starting point (the UI frames it that way), not a claim about behaviour, so
- it stays deterministic and never guesses intent. Falls back to
- ``shared_helper`` when the site has no usable label.
+ directory leaf) and suffix ``_helper``. It is an editable starting point
+ (the UI frames it that way), not a claim about behaviour, so it stays
+ deterministic and never guesses intent. Falls back to ``shared_helper``
+ when the site has no usable label.
+
+ Reads ``directory`` only. Plans stored before that key became the sole
+ namespace still carry a ``module`` community label, and it is precisely the
+ one that produced names like ``repowise_helper`` -- the repo naming its own
+ helper -- so it is not consulted as a fallback. ``directory`` was correct on
+ those rows too, which is why dropping the label needs no migration.
"""
- label = suggested_site.get("module") or suggested_site.get("directory") or ""
+ label = suggested_site.get("directory") or ""
leaf = label.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
- # Keep identifier-safe characters only; collapse the rest to single
- # underscores so a path leaf like ``api-client`` becomes ``api_client``.
- cleaned: list[str] = []
- prev_us = False
- for ch in leaf.lower():
- if ch.isalnum():
- cleaned.append(ch)
- prev_us = False
- elif not prev_us:
- cleaned.append("_")
- prev_us = True
- slug = "".join(cleaned).strip("_")
- # A leading digit is not a valid identifier start in most languages.
- if slug and slug[0].isdigit():
- slug = f"_{slug}"
+ slug = identifier_slug(leaf)
if not slug:
return "shared_helper"
return slug if slug.endswith("helper") else f"{slug}_helper"
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.py
index 65c3e7266..fb4cad67b 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -16,14 +16,21 @@ no suggestion.
Plan shape (open dict, no migration):
- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],
- "returns": [str, ...], "suggested_name": str | None}`` -- the lines to lift,
- the inferred signature, and an optional name (left ``None`` for the codegen /
- LLM step to choose).
+ "returns": [str, ...], "suggested_name": str}`` -- the lines to lift, the
+ inferred signature, and a deterministic starting name (see
+ ``_suggested_name``). Always a string: the field used to be a hardcoded
+ ``None`` here while Extract Helper computed one, so its meaning depended on
+ which detector wrote the plan and every surface fell through to a generic
+ "helper".
- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and
complexity the residual method sheds.
-- ``blast_radius`` = ``{"callers_count": int}`` -- extraction is local (a new
- private helper, the public method's signature is unchanged), so callers do
- not change; carried for the surfaces' consistency.
+- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a new
+ private helper, the public method's signature is unchanged), so nothing
+ outside the file moves. This is a *categorical* statement, not a count: it
+ replaced ``{"callers_count": 0}``, a hardcoded literal that no consumer could
+ tell apart from a measured zero. Every other detector's blast radius is
+ measured, so this one says in its own vocabulary that there is nothing to
+ measure.
"""
from __future__ import annotations
@@ -33,6 +40,7 @@ from typing import TYPE_CHECKING, Any
from ..complexity.languages import get_language_map
from ..dataflow import find_extractions
from .models import RefactoringContext, RefactoringSuggestion
+from .naming import identifier_slug
from .registry import RefactoringDetector, effort_bucket, register
if TYPE_CHECKING:
@@ -77,7 +85,7 @@ class ExtractMethodDetector(RefactoringDetector):
"span": {"start": best.start_line, "end": best.end_line},
"params": list(best.params),
"returns": list(best.returns),
- "suggested_name": None,
+ "suggested_name": self._suggested_name(analysis, best),
},
evidence={
"slice_nloc": best.slice_nloc,
@@ -85,7 +93,7 @@ class ExtractMethodDetector(RefactoringDetector):
},
impact_delta=round(float(impact), 3),
effort_bucket=effort_bucket(best.slice_nloc),
- blast_radius={"callers_count": 0},
+ blast_radius={"scope": "local"},
confidence=self._confidence(best),
source_biomarker=source,
)
@@ -116,6 +124,37 @@ class ExtractMethodDetector(RefactoringDetector):
best_source = getattr(f, "biomarker_type", "")
return best_impact, best_source
+ @staticmethod
+ def _suggested_name(analysis: FunctionAnalysis, extraction: Extraction) -> str:
+ """A deterministic starting name for the lifted helper.
+
+ Same posture as Extract Helper (see ``naming``): anchor the name to
+ something the plan already knows rather than guess what the block does.
+ The slice's OUT value is that anchor when there is exactly one -- a span
+ whose single product is ``average`` is, by construction, the code that
+ computes it, so ``compute_average`` describes it without inferring
+ intent. With no single OUT (a void slice, or several) the only certain
+ anchor left is the function the span came out of, which at least names
+ the helper for its context. Measured over the 854 stored plans on this
+ repo's index, 545 (64%) come from the OUT value and 309 from the
+ enclosing function.
+
+ **Not unique within a file, by design.** Two functions in one file can
+ each produce a value with the same name, and both spans then get the
+ same ``compute_*``: 28 of those 854 plans, across 14 files, collide with
+ a sibling that way (the fallback branch does not collide, since there is
+ one plan per function). Uniqueness would need a per-file suffix, which
+ would renumber existing names whenever a new plan appeared and churn
+ every persisted row. The name is a starting point every surface frames
+ as editable, so the surfaces say to rename on a clash instead.
+ """
+ if len(extraction.returns) == 1:
+ slug = identifier_slug(extraction.returns[0])
+ if slug:
+ return f"compute_{slug}"
+ slug = identifier_slug(analysis.name)
+ return f"{slug}_helper" if slug else "extracted_helper"
+
@staticmethod
def _confidence(extraction: Extraction) -> str:
"""High when the extraction is unambiguous -- it removes several decision
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index b80246e40..05db0ccb3 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -358,8 +358,12 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {
"extract_method": (
"Refactoring: EXTRACT METHOD. The target is one long function; the plan's "
"'span' gives the line range to lift into a new helper method in the same "
- "scope. Move exactly those lines into the helper, give it a clear name "
- "(use 'suggested_name' if set), pass the plan's 'params' as its arguments "
+ "scope. Move exactly those lines into the helper and name it: the plan's "
+ "'suggested_name' is a deterministic starting point, derived from the "
+ "slice's output value when it has exactly one and otherwise from the "
+ "enclosing function, so keep it unless the code clearly warrants a better "
+ "name -- and rename it if it collides with something already in the file, "
+ "which it can. Pass the plan's 'params' as its arguments "
"and return the plan's 'returns' value(s), and replace the original lines "
"with a call to it. Preserve behaviour exactly; change nothing outside the "
"span and the single call site."
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 77edeee39..40343a1fb 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -22,23 +22,42 @@ type without touching this module. For Extract Class:
For Extract Helper:
- ``plan`` = ``{"occurrences": [{"file": str, "line_start": int,
- "line_end": int}, ...], "suggested_site": {"module": str | None,
- "directory": str | None}, "duplicated_lines": int, "snippet": str | None,
+ "line_end": int}, ...], "suggested_site": {"directory": str | None},
+ "duplicated_lines": int, "snippet": str | None,
"snippet_start_line": int | None, "snippet_truncated": bool,
- "suggested_name": str | None}`` lists every site of the duplicated block,
+ "suggested_name": str}`` lists every site of the duplicated block,
where the shared helper should live, and the block itself: the anchor site's
source
text (identical across sites by definition, so stored once and capped at
``_MAX_SNIPPET_LINES``), the 1-indexed line it starts on, whether the cap
clipped it, and a deterministic starting name for the helper. ``snippet`` is
``None`` when the source could not be read (the plan still stands on its line
- ranges).
+ ranges). ``suggested_site`` is one namespace, the filesystem: it used to also
+ carry a graph community label under ``module``, which named a directory the
+ occurrences did not live in on every measured row. Plans stored before that
+ removal still carry the key; read ``directory``, which was correct on those
+ rows too.
- ``evidence`` = ``{"occurrence_count": int, "duplicated_lines": int,
"token_count": int, "co_change_count": int, "is_intra_file": bool}`` — the
size + activity signals that justify extracting a helper.
- ``blast_radius`` = ``{"files": [...], "file_count": int,
"co_change_count": int}`` — the other files that must change in lockstep.
+For Extract Method:
+
+- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],
+ "returns": [str, ...], "suggested_name": str}`` — the lines to lift, the
+ inferred signature, and a deterministic starting name (from the slice's single
+ OUT value, else the enclosing function). Always a string; it is an editable
+ starting point and is not unique within a file.
+- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` — the size and
+ complexity the residual method sheds.
+- ``blast_radius`` = ``{"scope": "local"}`` — the one type whose blast radius is
+ categorical rather than counted: extraction adds a private helper and changes
+ no signature, so nothing outside the file moves. It replaced a hardcoded
+ ``{"callers_count": 0}`` that no consumer could tell apart from a measured
+ zero.
+
For Move Method:
- ``plan`` = ``{"method": str, "from_class": str, "to_class": str,
@@ -116,11 +135,17 @@ class RefactoringContext:
# Consumed by the Extract Helper detector. Empty when duplication is
# disabled or the file has no clones.
clones: list[Any] = field(default_factory=list)
- # Repo-wide file -> community/module label map (a shared reference, not a
- # per-file copy). The Extract Helper detector reads it to place the
- # extracted helper at the community centroid of the clone's occurrences.
- # Empty on small repos that produced no community labels — the detector
- # then falls back to a shared-directory site.
+ # Repo-wide file -> graph community label map (a shared reference, not a
+ # per-file copy). Read by Split File alone, as an *affinity* proxy: two
+ # symbols calling into the same foreign cluster belong together, and a
+ # semantic cluster is the right unit for that question. It is not a path,
+ # so it must never name a location — Extract Helper used to site a new
+ # helper at the community centroid and thereby proposed directories the
+ # code was not in.
+ #
+ # Populated only by the full-index path; the incremental, re-score and
+ # ``repowise health`` paths leave it empty. Split File degrades to the
+ # callee's file path, so the signal weakens rather than changing namespace.
module_map: dict[str, str] = field(default_factory=dict)
# The repo's symbol/file graph (a ``networkx.DiGraph``, typed ``Any`` to
# avoid importing networkx into the model layer). A shared read-only
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/naming.py
new file mode 100644
index 000000000..c805eedbc
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/naming.py
@@ -0,0 +1,40 @@
+"""Deterministic identifier names for the code a plan asks you to create.
+
+Shared by the detectors that name a new unit (Extract Helper's shared helper,
+Extract Method's lifted helper) so one rule produces every ``suggested_name``
+in the payload. The alternative — each detector slugging its own way — is how a
+consumer ends up unable to say what a name means without knowing which detector
+wrote it, which is the defect this module exists to not repeat.
+
+Precision-first, and the same posture in both detectors: without semantics we
+cannot name a block for what it *does*, so a name is anchored to something the
+plan already knows for certain (where the helper lands, or the value it
+produces) and never guesses intent. It is an editable starting point, which is
+how every surface frames it, not a claim about behaviour.
+"""
+
+from __future__ import annotations
+
+
+def identifier_slug(label: str | None) -> str:
+ """*label* reduced to a lowercase identifier-safe slug, or ``""``.
+
+ Non-alphanumerics collapse to single underscores, so a path leaf like
+ ``api-client`` becomes ``api_client``. A leading digit is prefixed with an
+ underscore because it is not a valid identifier start in most languages.
+ """
+ if not label:
+ return ""
+ cleaned: list[str] = []
+ prev_us = False
+ for ch in label.lower():
+ if ch.isalnum():
+ cleaned.append(ch)
+ prev_us = False
+ elif not prev_us:
+ cleaned.append("_")
+ prev_us = True
+ slug = "".join(cleaned).strip("_")
+ if slug and slug[0].isdigit():
+ slug = f"_{slug}"
+ return slug
diff --git a/packages/ui/__tests__/refactoring/extract-method-types.test.ts b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
index 26c88c007..22a31d599 100644
--- a/packages/ui/__tests__/refactoring/extract-method-types.test.ts
+++ b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
@@ -21,12 +21,12 @@ function extractMethodPlanFixture(overrides: Partial<RefactoringPlan> = {}): Ref
span: { start: 30, end: 48 },
params: ["records", "threshold"],
returns: ["average"],
- suggested_name: null,
+ suggested_name: "compute_average",
},
evidence: { slice_nloc: 19, ccn_removed: 4 },
impact_delta: 1.5,
effort_bucket: "M",
- blast_radius: { callers_count: 0 },
+ blast_radius: { scope: "local" },
confidence: "high",
source_biomarker: "complex_method",
rank_score: 2.1,
@@ -40,6 +40,18 @@ describe("extract_method plan accessors", () => {
expect(em.span).toEqual({ start: 30, end: 48 });
expect(em.params).toEqual(["records", "threshold"]);
expect(em.returns).toEqual(["average"]);
+ expect(em.suggested_name).toBe("compute_average");
+ });
+
+ it("still degrades to null for a plan stored before names were computed", () => {
+ // Every extract_method plan written before the backend computed a name has
+ // `suggested_name: null`; the accessor must keep normalising it so the
+ // render fallbacks below stay reachable for those rows.
+ const em = extractMethodPlan(
+ extractMethodPlanFixture({
+ plan: { span: { start: 30, end: 48 }, params: [], returns: [], suggested_name: null },
+ }),
+ );
expect(em.suggested_name).toBeNull();
});
diff --git a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
new file mode 100644
index 000000000..2e8758d66
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
@@ -0,0 +1,99 @@
+/**
+ * The published surfaces for two plan fields that used to be constants.
+ *
+ * Fixing them in the backend alone would be half a fix: `suggested_name` was
+ * `null` on every extract_method plan, so the prompt builder and the plan
+ * detail always fell through to a generic "helper" — the user-facing
+ * consequence lived here, not in Python. And `suggested_site` carried a graph
+ * community label under `module` alongside a filesystem `directory`, which
+ * `helperSite` preferred; plans stored before that removal still carry it.
+ */
+import { describe, it, expect } from "vitest";
+import { helperSite, extractMethodPlan, type RefactoringPlan } from "../../src/refactoring/types";
+import { buildRefactoringPlanPrompt } from "../../src/health/ai-prompt-builder";
+
+function helperPlan(suggested_site: Record<string, unknown>): RefactoringPlan {
+ return {
+ id: "p1",
+ refactoring_type: "extract_helper",
+ file_path: "pkg/api/a.py",
+ target_symbol: "a.py:10-25",
+ line_start: 10,
+ line_end: 25,
+ plan: {
+ occurrences: [
+ { file: "pkg/api/a.py", line_start: 10, line_end: 25 },
+ { file: "pkg/core/b.py", line_start: 40, line_end: 55 },
+ ],
+ suggested_site,
+ duplicated_lines: 16,
+ suggested_name: "pkg_helper",
+ },
+ evidence: { duplicated_lines: 16, occurrence_count: 2 },
+ impact_delta: 0.9,
+ effort_bucket: "S",
+ blast_radius: { files: ["pkg/core/b.py"], file_count: 1 },
+ confidence: "high",
+ source_biomarker: "dry_violation",
+ rank_score: 1.4,
+ };
+}
+
+function methodPlan(suggested_name: string | null): RefactoringPlan {
+ return {
+ id: "p2",
+ refactoring_type: "extract_method",
+ file_path: "pkg/pipeline.py",
+ target_symbol: "run_pipeline",
+ line_start: 10,
+ line_end: 80,
+ plan: {
+ span: { start: 30, end: 48 },
+ params: ["records", "threshold"],
+ returns: ["average"],
+ suggested_name,
+ },
+ evidence: { slice_nloc: 19, ccn_removed: 4 },
+ impact_delta: 1.5,
+ effort_bucket: "M",
+ blast_radius: { scope: "local" },
+ confidence: "high",
+ source_biomarker: "complex_method",
+ rank_score: 2.1,
+ };
+}
+
+describe("helperSite namespace", () => {
+ it("reads the directory, the only namespace a plan now carries", () => {
+ expect(helperSite(helperPlan({ directory: "pkg" }))).toBe("pkg");
+ });
+
+ it("prefers the directory over a legacy community label on a stored plan", () => {
+ // The measured shape: on 905 of 905 labelled rows the label named a
+ // directory no occurrence lived in, while `directory` was correct. Reading
+ // the label first is what put `ui` on a block spanning three packages.
+ expect(helperSite(helperPlan({ module: "ui", directory: "pkg" }))).toBe("pkg");
+ });
+
+ it("salvages the label only when a legacy row has no directory at all", () => {
+ expect(helperSite(helperPlan({ module: "ui", directory: null }))).toBe("ui");
+ });
+
+ it("returns null when the plan carries no site", () => {
+ expect(helperSite(helperPlan({}))).toBeNull();
+ });
+});
+
+describe("extract_method suggested_name reaches the rendered prompt", () => {
+ it("uses the computed name instead of the generic fallback", () => {
+ const prompt = buildRefactoringPlanPrompt({ plan: methodPlan("compute_average") });
+ expect(prompt).toContain("compute_average");
+ expect(prompt).not.toContain("a clearly named helper");
+ });
+
+ it("keeps the generic fallback for a plan stored before names were computed", () => {
+ const prompt = buildRefactoringPlanPrompt({ plan: methodPlan(null) });
+ expect(prompt).toContain("a clearly named helper");
+ expect(extractMethodPlan(methodPlan(null)).suggested_name).toBeNull();
+ });
+});
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 65609b3be..44dd0260a 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -107,12 +107,18 @@ export function extractHelperOccurrences(plan: RefactoringPlan): ExtractHelperOc
});
}
+/** Where the shared helper should live — a directory.
+ *
+ * `directory` is the only namespace a plan carries. Plans stored before that
+ * also carried `module`, a graph community label that named a directory the
+ * occurrences did not live in, so it is read last and only as a salvage for an
+ * old row with no `directory`. */
export function helperSite(plan: RefactoringPlan): string | null {
const site = plan.plan?.suggested_site as Record<string, unknown> | undefined;
if (!site) return null;
- const module = typeof site.module === "string" ? site.module : null;
const dir = typeof site.directory === "string" ? site.directory : null;
- return module ?? dir;
+ const legacyModule = typeof site.module === "string" ? site.module : null;
+ return dir ?? legacyModule;
}
export interface ExtractHelperDetail {
diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.py
index 8bac7ebaa..1a5a6ba8e 100644
--- a/tests/unit/cli/test_refactoring_targets_render.py
+++ b/tests/unit/cli/test_refactoring_targets_render.py
@@ -66,3 +66,55 @@ def test_markdown_renders_both_sections(capsys):
assert "C.envious" in text and "`T (t.py)`" in text
assert "## Break Cycle plans" in text
assert "invert b.py -> a.py" in text
+
+
+def _extract_helper(suggested_site: dict) -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="extract_helper",
+ file_path="pkg/api/a.py",
+ target_symbol="a.py:10-25",
+ line_start=10,
+ line_end=25,
+ plan={
+ "occurrences": [
+ {"file": "pkg/api/a.py", "line_start": 10, "line_end": 25},
+ {"file": "pkg/core/b.py", "line_start": 40, "line_end": 55},
+ ],
+ "suggested_site": suggested_site,
+ "duplicated_lines": 16,
+ "suggested_name": "pkg_helper",
+ },
+ evidence={"duplicated_lines": 16, "occurrence_count": 2, "co_change_count": 0},
+ impact_delta=0.9,
+ effort_bucket="S",
+ blast_radius={"files": ["pkg/core/b.py"], "file_count": 1},
+ confidence="high",
+ source_biomarker="dry_violation",
+ )
+
+
+def test_helper_site_renders_the_directory(capsys):
+ """``directory`` is the only namespace a plan now carries."""
+ _render_refactoring_targets([], [], [_extract_helper({"directory": "pkg/api"})], fmt="md")
+ assert "near `pkg/api`" in capsys.readouterr().out
+
+
+def test_helper_site_prefers_directory_over_a_legacy_community_label(capsys):
+ """Plans stored before the community label was dropped still carry
+ ``module``, and it named a directory the occurrences did not live in on
+ every measured row (905 of 905). Rendering it is what told users to put a
+ shared helper in a package two thirds of its callers are not in, so the
+ directory must win on those rows too.
+ """
+ legacy = _extract_helper({"module": "ui", "directory": "pkg/api"})
+ _render_refactoring_targets([], [], [legacy], fmt="md")
+ text = capsys.readouterr().out
+ assert "near `pkg/api`" in text
+ assert "near `ui`" not in text
+
+
+def test_helper_site_falls_back_when_a_legacy_row_has_no_directory(capsys):
+ """Salvage only: a legacy row with no directory still renders something."""
+ legacy = _extract_helper({"module": "ui", "directory": None})
+ _render_refactoring_targets([], [], [legacy], fmt="md")
+ assert "near `ui`" in capsys.readouterr().out
diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.py
index 1440a8567..a0258245f 100644
--- a/tests/unit/health/test_refactoring_extract_helper.py
+++ b/tests/unit/health/test_refactoring_extract_helper.py
@@ -336,26 +336,53 @@ def test_confidence_medium_when_dormant():
# ---- suggested site ------------------------------------------------------
-def test_suggested_site_community_centroid():
- pair = _pair("api/a.py", "core/b.py", 10, 25, 40, 55)
- module_map = {"api/a.py": "api", "core/b.py": "api"}
+def _site_for(module_map: dict[str, str] | None) -> dict:
+ """The suggested site for one fixed cross-package clone, under *module_map*.
+
+ The occurrences deliberately live in different top-level packages, so the
+ only honest shared directory is the shallow ``pkg`` -- the case where a
+ community label reads nicer and is wrong.
+ """
+ pair = _pair("pkg/api/a.py", "pkg/core/b.py", 10, 25, 40, 55)
s = next(
s
- for s in detect_refactorings(_ctx("api/a.py", [pair], module_map=module_map))
+ for s in detect_refactorings(_ctx("pkg/api/a.py", [pair], module_map=module_map))
if s.refactoring_type == "extract_helper"
)
- assert s.plan["suggested_site"]["module"] == "api"
+ return s.plan
-def test_suggested_site_directory_fallback():
+def test_suggested_site_is_the_shared_directory_only():
+ plan = _site_for(None)
+ assert plan["suggested_site"] == {"directory": "pkg"}
+ assert plan["suggested_name"] == "pkg_helper"
+
+
+def test_suggested_site_ignores_a_hostile_community_label():
+ """The load-bearing property: the plan no longer depends on which write
+ path produced it.
+
+ ``module_map`` is populated by the full-index path alone -- the incremental,
+ re-score and ``repowise health`` paths leave it empty -- so a label-derived
+ site made the payload's namespace a function of the last writer. Here the
+ label ``ui`` is on *neither* occurrence's path, which is the shape measured
+ on the real index (905 of 905 labelled plans named a directory no
+ occurrence lived in). A detector that still read it would answer ``ui``.
+ """
+ hostile = {"pkg/api/a.py": "ui", "pkg/core/b.py": "ui"}
+ assert _site_for(hostile) == _site_for(None)
+ assert "module" not in _site_for(hostile)["suggested_site"]
+ assert _site_for(hostile)["suggested_name"] == "pkg_helper"
+
+
+def test_suggested_site_prefers_the_deepest_shared_directory():
pair = _pair("pkg/sub/a.py", "pkg/sub/b.py", 10, 25, 40, 55)
s = next(
s
for s in detect_refactorings(_ctx("pkg/sub/a.py", [pair]))
if s.refactoring_type == "extract_helper"
)
- assert s.plan["suggested_site"]["module"] is None
- assert s.plan["suggested_site"]["directory"] == "pkg/sub"
+ assert s.plan["suggested_site"] == {"directory": "pkg/sub"}
def test_common_directory_helper():
@@ -443,17 +470,25 @@ def test_suggested_name_from_directory():
def test_suggested_name_helper_unit():
- assert _suggested_name({"module": "api", "directory": None}) == "api_helper"
- # module wins over directory
- assert _suggested_name({"module": "core", "directory": "pkg/sub"}) == "core_helper"
+ assert _suggested_name({"directory": "api"}) == "api_helper"
# path leaf, hyphens normalised
- assert _suggested_name({"module": None, "directory": "web/api-client"}) == "api_client_helper"
+ assert _suggested_name({"directory": "web/api-client"}) == "api_client_helper"
# leading digit made identifier-safe
- assert _suggested_name({"module": "3d", "directory": None}) == "_3d_helper"
+ assert _suggested_name({"directory": "3d"}) == "_3d_helper"
# already ends in helper -> no double suffix
- assert _suggested_name({"module": "render_helper", "directory": None}) == "render_helper"
+ assert _suggested_name({"directory": "render_helper"}) == "render_helper"
# no usable label -> stable fallback
- assert _suggested_name({"module": None, "directory": None}) == "shared_helper"
+ assert _suggested_name({"directory": None}) == "shared_helper"
+
+
+def test_suggested_name_ignores_a_legacy_community_label():
+ """A plan stored before the community label was dropped still carries
+ ``module``. It is the key that produced names like ``repowise_helper`` --
+ the repo naming its own helper -- so it must not be revived as a fallback;
+ ``directory`` was the correct value on those rows and is what wins."""
+ assert _suggested_name({"module": "core", "directory": "pkg/sub"}) == "sub_helper"
+ # Even with no directory at all, the label is not consulted.
+ assert _suggested_name({"module": "repowise", "directory": None}) == "shared_helper"
# ---- determinism ---------------------------------------------------------
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 0077805be..86d537851 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -349,10 +349,53 @@ def test_detector_emits_suggestion_for_flagged_function():
assert set(s.plan) == {"span", "params", "returns", "suggested_name"}
assert set(s.plan["span"]) == {"start", "end"}
assert set(s.evidence) == {"slice_nloc", "ccn_removed"}
- assert s.blast_radius == {"callers_count": 0}
+ # A categorical claim, not a count: extraction is local, so there is nothing
+ # to measure. The old ``{"callers_count": 0}`` was a hardcoded literal that
+ # no consumer could tell apart from a measured zero.
+ assert s.blast_radius == {"scope": "local"}
+ assert "callers_count" not in s.blast_radius
assert s.confidence in ("medium", "high")
+def test_plan_carries_a_computed_name_not_a_hardcoded_none():
+ """``suggested_name`` was ``None`` on every extract_method plan ever stored
+ (854 of 854 on this repo's index) while Extract Helper computed one, so the
+ field's meaning depended on which detector wrote it and every surface fell
+ through to a generic "helper". It is now always a real identifier."""
+ findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]
+ s = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))[0]
+ # The slice's single OUT value is ``average``, so the span is by
+ # construction the code that computes it.
+ assert s.plan["returns"] == ["average"]
+ assert s.plan["suggested_name"] == "compute_average"
+
+
+class _Extraction:
+ def __init__(self, returns):
+ self.returns = list(returns)
+
+
+class _Analysis:
+ def __init__(self, name):
+ self.name = name
+
+
+def test_suggested_name_unit():
+ name = ExtractMethodDetector._suggested_name
+ # Exactly one OUT -> name the helper for what it produces.
+ assert name(_Analysis("process"), _Extraction(["average"])) == "compute_average"
+ # Non-identifier characters normalised through the shared slug.
+ assert name(_Analysis("p"), _Extraction(["total-count"])) == "compute_total_count"
+ # No single OUT -> fall back to the enclosing function, the only other
+ # anchor known for certain.
+ assert name(_Analysis("run_pipeline"), _Extraction([])) == "run_pipeline_helper"
+ assert name(_Analysis("run_pipeline"), _Extraction(["a", "b"])) == "run_pipeline_helper"
+ # A return name that slugs to nothing must not yield "compute_".
+ assert name(_Analysis("process"), _Extraction(["___"])) == "process_helper"
+ # Nothing usable at all -> a stable, still-valid identifier.
+ assert name(_Analysis(""), _Extraction([])) == "extracted_helper"
+
+
def test_detector_silent_without_matching_finding():
# The function is analysed but no method biomarker fired -> no suggestion.
suggestions = ExtractMethodDetector().detect(_ctx(_PROCESS, findings=[]))
diff --git a/tests/unit/health/test_refactoring_naming.py b/tests/unit/health/test_refactoring_naming.py
new file mode 100644
index 000000000..f69ee131a
--- /dev/null
+++ b/tests/unit/health/test_refactoring_naming.py
@@ -0,0 +1,38 @@
+"""The shared identifier slug both name-producing detectors run through.
+
+It exists so ``suggested_name`` means one thing across the payload rather than
+one thing per detector.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.refactoring.naming import identifier_slug
+
+
+def test_lowercases_and_keeps_alphanumerics():
+ assert identifier_slug("Providers") == "providers"
+ assert identifier_slug("http2") == "http2"
+
+
+def test_collapses_non_alphanumeric_runs_to_single_underscores():
+ assert identifier_slug("api-client") == "api_client"
+ assert identifier_slug("a..--..b") == "a_b"
+ assert identifier_slug("pkg/sub") == "pkg_sub"
+
+
+def test_strips_leading_and_trailing_separators():
+ assert identifier_slug("--api--") == "api"
+ assert identifier_slug("_private_") == "private"
+
+
+def test_leading_digit_is_made_identifier_safe():
+ # Not a valid identifier start in most languages.
+ assert identifier_slug("3d") == "_3d"
+ assert identifier_slug("2fa-token") == "_2fa_token"
+
+
+def test_unusable_input_returns_empty_so_callers_can_pick_a_fallback():
+ assert identifier_slug("") == ""
+ assert identifier_slug(None) == ""
+ assert identifier_slug("---") == ""
+ assert identifier_slug("...") == ""