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.

feat(refactoring): show the duplicated block in extract-helper plans (#1039)

Raghav Chamadiya5506f811a113
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 38b7fd286..577d364dc 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -119,6 +119,21 @@ def _fallback_module(rel_path: str) -> str | None:
return head or None
+def _read_source_lines(abs_path: str) -> list[str] | None:
+ """Read a file's source as 1-indexed lines for the Extract Helper snippet.
+
+ Failure-isolated: a read or decode error yields ``None`` (the detector then
+ omits the snippet and keeps its line ranges), never an exception into the
+ health pass. Decodes UTF-8 leniently since the snippet is for display, not
+ re-parsing.
+ """
+ try:
+ text = Path(abs_path).read_bytes().decode("utf-8", errors="replace")
+ except OSError:
+ return None
+ return text.splitlines()
+
+
class _ImportEdgeView:
"""Thin ``HasEdge`` adapter over a NetworkX DiGraph.
@@ -909,6 +924,11 @@ class HealthAnalyzer:
),
function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),
blame_index=blame_index,
+ # Source is threaded only for clone-bearing files (the Extract Helper
+ # detector's snippet). Reading it unconditionally would put a
+ # repo-sized read back into the per-file path; gating on clones keeps
+ # it proportional to the small set of files that actually carry one.
+ source_lines=_read_source_lines(pf.file_info.abs_path) if clones else None,
)
suggestions = detect_refactorings(
rctx,
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 c860287ab..c4c9bb928 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
@@ -61,6 +61,11 @@ _ACTIVE_CO_CHANGE = 3
# same block — matches the duplication merger's one-line window slack.
_REGION_SLACK = 1
+# Cap on the stored snippet. An XL clone block can be hundreds of lines; the
+# snippet is for a glance ("this is the duplicated code"), not the whole thing,
+# so it is clipped and the plan flags that it was.
+_MAX_SNIPPET_LINES = 40
+
def _is_test_path(path: str) -> bool:
"""Conservative test-file check (mirrors the engine's ``_is_test_file``).
@@ -241,10 +246,16 @@ 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)
+ 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],
- "suggested_site": self._suggested_site(ctx, occ_files),
+ "suggested_site": suggested_site,
"duplicated_lines": duplicated_lines,
+ "snippet": snippet,
+ "snippet_start_line": snippet_start,
+ "snippet_truncated": snippet_truncated,
+ "suggested_name": _suggested_name(suggested_site),
}
evidence = {
"occurrence_count": len(occurrences),
@@ -294,6 +305,34 @@ class ExtractHelperDetector(RefactoringDetector):
module = min(counts, key=lambda m: (-counts[m], m))
return {"module": module, "directory": _common_directory(occ_files)}
+ @staticmethod
+ def _snippet_for(
+ ctx: RefactoringContext, anchor_region: tuple[int, int]
+ ) -> tuple[str | None, int | None, bool]:
+ """The duplicated block's source text, read from the anchor file.
+
+ The block is identical across every site by definition (it *is* the
+ clone), so it is stored once, taken from the anchor region on this file
+ (the file the suggestion is emitted from). Clipped at
+ ``_MAX_SNIPPET_LINES`` with a flag when it overran. Returns
+ ``(None, None, False)`` when no source was threaded (non-clone file, or
+ an unreadable one), leaving the plan on its line ranges alone.
+ """
+ lines = ctx.source_lines
+ if not lines:
+ return None, None, False
+ start, end = anchor_region
+ # Clamp to the file; clone ranges are 1-indexed and inclusive.
+ lo = max(start, 1)
+ hi = min(end, len(lines))
+ if hi < lo:
+ return None, None, False
+ block = lines[lo - 1 : hi]
+ truncated = len(block) > _MAX_SNIPPET_LINES
+ if truncated:
+ block = block[:_MAX_SNIPPET_LINES]
+ return "\n".join(block), lo, truncated
+
@staticmethod
def _impact_for_dry_violation(ctx: RefactoringContext) -> list[tuple[int, int, float]]:
"""The file's ``dry_violation`` findings as (line_start, line_end,
@@ -356,6 +395,38 @@ def _merge_ranges_per_file(
return sorted(out)
+def _suggested_name(suggested_site: dict[str, str | None]) -> str:
+ """A deterministic starting name for the extracted helper.
+
+ Precision-first: without semantics we cannot name the block for what it
+ *does*, so we anchor the name to where the helper will live (the shared
+ 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.
+ """
+ label = suggested_site.get("module") or 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}"
+ if not slug:
+ return "shared_helper"
+ return slug if slug.endswith("helper") else f"{slug}_helper"
+
+
def _common_directory(paths: list[str]) -> str | None:
"""Longest shared directory prefix of *paths* (POSIX), or ``None`` when
they share no directory. Component-wise, never mid-segment."""
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 6a39b3133..77edeee39 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -23,8 +23,16 @@ For Extract Helper:
- ``plan`` = ``{"occurrences": [{"file": str, "line_start": int,
"line_end": int}, ...], "suggested_site": {"module": str | None,
- "directory": str | None}, "duplicated_lines": int}`` — every site of the
- duplicated block and where the shared helper should live.
+ "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,
+ 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).
- ``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.
@@ -147,6 +155,13 @@ class RefactoringContext:
# index) is the documented "no signal" outcome — the detector degrades to its
# call/import signals only.
blame_index: Any = None
+ # This file's source as 1-indexed lines (``source_lines[0]`` is line 1). The
+ # engine reads it only for files that carry clone pairs, so the cost stays
+ # proportional to clone-bearing files rather than the whole repo. The Extract
+ # Helper detector slices the anchor block out of it for the plan's snippet;
+ # every other detector ignores it. ``None`` when the file was not read (no
+ # clones) or the read failed; the detector then omits the snippet.
+ source_lines: list[str] | None = None
@dataclass
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index 97e4eef50..aa56dfbbc 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -7,6 +7,7 @@ import {
cutEdges,
cycleMembers,
extractClassGroups,
+ extractHelperDetail,
extractHelperOccurrences,
extractMethodPlan,
helperSite,
@@ -69,6 +70,35 @@ function FileRef({
);
}
+/** A read-only source block with a line-number gutter. Scrolls horizontally on
+ * its own so a long line never widens the page. The gutter counts up from
+ * `startLine` so the numbers match the file the block came from. */
+function CodeBlock({ code, startLine }: { code: string; startLine: number | null }) {
+ const lines = code.split("\n");
+ const base = startLine ?? 1;
+ const gutterWidth = `${String(base + lines.length - 1).length}ch`;
+ return (
+ <div className="overflow-x-auto rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
+ <pre className="py-2 text-2xs leading-relaxed">
+ <code className="block font-mono">
+ {lines.map((ln, i) => (
+ <div key={i} className="flex px-3">
+ <span
+ className="mr-3 shrink-0 select-none text-right tabular-nums text-[var(--color-text-tertiary)]"
+ style={{ minWidth: gutterWidth }}
+ aria-hidden
+ >
+ {base + i}
+ </span>
+ <span className="whitespace-pre text-[var(--color-text-secondary)]">{ln || " "}</span>
+ </div>
+ ))}
+ </code>
+ </pre>
+ </div>
+ );
+}
+
/**
* The concrete, type-specific body of a refactoring plan: split groups as a
* tree, the move as an arrow, clone occurrences as a list, the cycle as cut
@@ -148,12 +178,19 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
if (plan.refactoring_type === "extract_helper") {
const occ = extractHelperOccurrences(plan);
const site = helperSite(plan);
+ const detail = extractHelperDetail(plan);
+ const dupLines = Number(plan.evidence?.duplicated_lines ?? 0);
+ const helperName = detail.suggestedName ?? "helper";
+ const call = `${helperName}()`;
return (
<div className="space-y-3">
{hideIntro ? null : (
<p className="text-xs text-[var(--color-text-tertiary)]">
- The same block appears in {occ.length} place{occ.length === 1 ? "" : "s"}. Extract
- it once
+ The same {dupLines ? `${dupLines}-line ` : ""}block appears in {occ.length} place
+ {occ.length === 1 ? "" : "s"}. Extract it once into{" "}
+ <code className="rounded bg-[var(--color-bg-elevated)] px-1 py-0.5 text-2xs text-[var(--color-text-primary)]">
+ {call}
+ </code>
{site ? (
<>
{" "}
@@ -166,18 +203,74 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
.
</p>
)}
- <ul className="divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
- {occ.map((o, i) => (
- <li key={i} className="flex items-center justify-between gap-3 px-3.5 py-2.5">
- <span className="min-w-0 flex-1">
- <FileRef path={o.file} line={o.line_start} fileHref={fileHref} className="block truncate" />
- </span>
- <span className="shrink-0 text-2xs tabular-nums text-[var(--color-text-tertiary)]">
- lines {o.line_start}–{o.line_end}
- </span>
- </li>
- ))}
- </ul>
+
+ {/* Collapse at a glance: N duplicate copies → 1 shared helper. */}
+ <div className="flex items-center gap-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
+ <div className="min-w-0 flex-1">
+ <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Today
+ </div>
+ <div className="text-xs font-semibold text-[var(--color-text-primary)]">
+ {occ.length} duplicate cop{occ.length === 1 ? "y" : "ies"}
+ </div>
+ </div>
+ <ArrowRight className="h-4 w-4 shrink-0" style={{ color: accent }} aria-hidden />
+ <div className="min-w-0 flex-1 text-right">
+ <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ After
+ </div>
+ <code className="text-xs font-semibold text-[var(--color-text-primary)]">{call}</code>
+ </div>
+ </div>
+
+ {/* The duplicated block itself, shown once (identical across sites). */}
+ {detail.snippet ? (
+ <div className="space-y-1.5">
+ <div className="flex items-center gap-1.5 text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <Scissors className="h-3.5 w-3.5" style={{ color: accent }} aria-hidden />
+ The duplicated block
+ {detail.snippetTruncated ? (
+ <span className="normal-case tracking-normal text-[var(--color-text-tertiary)]">
+ (first lines shown)
+ </span>
+ ) : null}
+ </div>
+ <CodeBlock code={detail.snippet} startLine={detail.snippetStartLine} />
+ </div>
+ ) : null}
+
+ {/* Every site, as a jump link, with the call that replaces it. */}
+ <div className="space-y-1.5">
+ <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Replace at {occ.length} site{occ.length === 1 ? "" : "s"}
+ </div>
+ <ul className="divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
+ {occ.map((o, i) => (
+ <li key={i} className="flex items-center justify-between gap-3 px-3.5 py-2.5">
+ <span className="min-w-0 flex-1">
+ <FileRef
+ path={o.file}
+ line={o.line_start}
+ fileHref={fileHref}
+ className="block truncate"
+ />
+ </span>
+ <span className="flex shrink-0 items-center gap-2">
+ <span className="text-2xs tabular-nums text-[var(--color-text-tertiary)]">
+ lines {o.line_start}–{o.line_end}
+ </span>
+ <ArrowRight
+ className="h-3 w-3 text-[var(--color-text-tertiary)]"
+ aria-hidden
+ />
+ <code className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]">
+ {call}
+ </code>
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
</div>
);
}
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 203fd8354..213beb440 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -103,6 +103,35 @@ export function helperSite(plan: RefactoringPlan): string | null {
return module ?? dir;
}
+export interface ExtractHelperDetail {
+ /** The duplicated block's source (the anchor site, identical across sites),
+ * or `null` when the backend could not read it. */
+ snippet: string | null;
+ /** 1-indexed line the snippet starts on, for the gutter. */
+ snippetStartLine: number | null;
+ /** Whether the block was clipped at the size cap. */
+ snippetTruncated: boolean;
+ /** A deterministic starting name for the helper, e.g. `foo_helper`. */
+ suggestedName: string | null;
+}
+
+/** The block-level detail added to an extract-helper plan: the snippet itself,
+ * a starting name, and whether it was clipped. Read defensively; every field
+ * degrades to a null/false absence rather than throwing. */
+export function extractHelperDetail(plan: RefactoringPlan): ExtractHelperDetail {
+ const p = (plan.plan ?? {}) as Record<string, unknown>;
+ const snippet = typeof p.snippet === "string" && p.snippet.length > 0 ? p.snippet : null;
+ const start = Number(p.snippet_start_line ?? 0);
+ return {
+ snippet,
+ snippetStartLine: snippet && start > 0 ? start : null,
+ snippetTruncated: p.snippet_truncated === true,
+ suggestedName: typeof p.suggested_name === "string" && p.suggested_name.length > 0
+ ? p.suggested_name
+ : null,
+ };
+}
+
export interface MoveTarget {
method: string;
from_class: string;
@@ -440,7 +469,13 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
case "extract_helper": {
const occ = extractHelperOccurrences(plan).length;
const lines = Number(plan.evidence?.duplicated_lines ?? 0);
- if (occ) wins.push({ label: `${occ} duplicate cop${occ === 1 ? "y" : "ies"} collapsed to one` });
+ const name = extractHelperDetail(plan).suggestedName;
+ if (occ)
+ wins.push({
+ label: name
+ ? `${occ} duplicate cop${occ === 1 ? "y" : "ies"} collapsed into ${name}()`
+ : `${occ} duplicate cop${occ === 1 ? "y" : "ies"} collapsed to one`,
+ });
if (lines) wins.push({ label: `~${lines} duplicated lines removed` });
break;
}
diff --git a/tests/unit/health/test_refactoring_extract_helper.py b/tests/unit/health/test_refactoring_extract_helper.py
index 5f3d59f7a..80db015d2 100644
--- a/tests/unit/health/test_refactoring_extract_helper.py
+++ b/tests/unit/health/test_refactoring_extract_helper.py
@@ -18,8 +18,10 @@ from repowise.core.analysis.health.refactoring import (
registered_detectors,
)
from repowise.core.analysis.health.refactoring.extract_helper import (
+ _MAX_SNIPPET_LINES,
_common_directory,
_merge_ranges_per_file,
+ _suggested_name,
)
@@ -64,6 +66,7 @@ def _ctx(
*,
findings: list | None = None,
module_map: dict[str, str] | None = None,
+ source_lines: list[str] | None = None,
) -> RefactoringContext:
return RefactoringContext(
file_path=file_path,
@@ -74,6 +77,7 @@ def _ctx(
dependents_count=0,
clones=clones,
module_map=module_map or {},
+ source_lines=source_lines,
)
@@ -339,6 +343,97 @@ def test_common_directory_helper():
assert _common_directory(["x.py", "a/y.py"]) is None
+# ---- snippet + suggested name --------------------------------------------
+
+
+def _numbered_source(n: int) -> list[str]:
+ # 1-indexed content so a slice is easy to assert: line k reads "line k".
+ return [f"line {i}" for i in range(1, n + 1)]
+
+
+def test_snippet_sliced_from_anchor_region():
+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)
+ s = next(
+ s
+ for s in detect_refactorings(
+ _ctx("pkg/a.py", [pair], source_lines=_numbered_source(80))
+ )
+ if s.refactoring_type == "extract_helper"
+ )
+ assert s.plan["snippet_start_line"] == 10
+ assert s.plan["snippet_truncated"] is False
+ lines = s.plan["snippet"].split("\n")
+ assert lines[0] == "line 10"
+ assert lines[-1] == "line 25"
+ assert len(lines) == 16
+
+
+def test_snippet_none_without_source():
+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)
+ s = next(
+ s
+ for s in detect_refactorings(_ctx("pkg/a.py", [pair]))
+ if s.refactoring_type == "extract_helper"
+ )
+ assert s.plan["snippet"] is None
+ assert s.plan["snippet_start_line"] is None
+ assert s.plan["snippet_truncated"] is False
+
+
+def test_snippet_capped_and_flagged():
+ # A 60-line block clips to the cap and flags it.
+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 69, 100, 159)
+ s = next(
+ s
+ for s in detect_refactorings(
+ _ctx("pkg/a.py", [pair], source_lines=_numbered_source(200))
+ )
+ if s.refactoring_type == "extract_helper"
+ )
+ assert s.plan["snippet_truncated"] is True
+ assert len(s.plan["snippet"].split("\n")) == _MAX_SNIPPET_LINES
+
+
+def test_snippet_clamped_to_short_file():
+ # Clone range runs past EOF (a stale-ish range); clamp, never IndexError.
+ pair = _pair("pkg/a.py", "pkg/b.py", 10, 25, 40, 55)
+ s = next(
+ s
+ for s in detect_refactorings(
+ _ctx("pkg/a.py", [pair], source_lines=_numbered_source(18))
+ )
+ if s.refactoring_type == "extract_helper"
+ )
+ lines = s.plan["snippet"].split("\n")
+ assert lines[0] == "line 10"
+ assert lines[-1] == "line 18"
+
+
+def test_suggested_name_from_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"
+ )
+ # directory site "pkg/sub" -> leaf "sub"
+ assert s.plan["suggested_name"] == "sub_helper"
+
+
+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"
+ # path leaf, hyphens normalised
+ assert _suggested_name({"module": None, "directory": "web/api-client"}) == "api_client_helper"
+ # leading digit made identifier-safe
+ assert _suggested_name({"module": "3d", "directory": None}) == "_3d_helper"
+ # already ends in helper -> no double suffix
+ assert _suggested_name({"module": "render_helper", "directory": None}) == "render_helper"
+ # no usable label -> stable fallback
+ assert _suggested_name({"module": None, "directory": None}) == "shared_helper"
+
+
# ---- determinism ---------------------------------------------------------