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(health): add web Refactoring tab with ranked plan cards and agent export (#589)

Raghav Chamadiyaa83475385d37
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.py
index 5d78396dc..400a3bc38 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py
@@ -884,6 +884,25 @@ async def upsert_refactoring_suggestions(
await session.flush()
+async def get_refactoring_suggestion(
+ session: AsyncSession,
+ repository_id: str,
+ suggestion_id: str,
+) -> RefactoringSuggestion | None:
+ """Return one refactoring suggestion by id, scoped to *repository_id*.
+
+ Powers the web tab's plan-detail drill-down (and any deep link to a single
+ plan). Returns ``None`` when the id is unknown or belongs to another repo.
+ """
+ result = await session.execute(
+ select(RefactoringSuggestion).where(
+ RefactoringSuggestion.repository_id == repository_id,
+ RefactoringSuggestion.id == suggestion_id,
+ )
+ )
+ return result.scalar_one_or_none()
+
+
async def get_refactoring_suggestions(
session: AsyncSession,
repository_id: str,
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 0800c2d65..061d920b5 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -54,6 +54,7 @@ from repowise.server.routers import (
owners,
pages,
providers,
+ refactoring,
repos,
search,
security,
@@ -415,6 +416,7 @@ def create_app() -> FastAPI:
app.include_router(costs.router)
app.include_router(security.router)
app.include_router(blast_radius.router)
+ app.include_router(refactoring.router)
app.include_router(knowledge_map.router)
app.include_router(workspace.router)
app.include_router(owners.router)
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
new file mode 100644
index 000000000..1e5b51bfa
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -0,0 +1,225 @@
+"""/api/repos/{repo_id}/refactoring — deterministic refactoring plans.
+
+The refactoring layer writes one structured ``RefactoringSuggestion`` row per
+opportunity (Extract Class, Extract Helper, Move Method, Break Cycle). These
+endpoints read those rows from SQL and re-apply the unified rank so the order
+the web tab shows matches every other surface (CLI / MCP): a plan on a central
+hub file outranks the same plan on a leaf, blast radius amplifies, confidence
+breaks ties.
+
+No on-disk work happens here, so this works on hosted backends without a
+checkout — the same property the C4 endpoints rely on.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, Field
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.rank import rank_suggestions, score
+
+
+def blast_files(sug: RefactoringSuggestion) -> list[str]:
+ """The other files a plan drags along, from whichever blast-radius shape it
+ carries — used to scope the detail endpoint's centrality lookup."""
+ files = (sug.blast_radius or {}).get("files")
+ return [f for f in files if isinstance(f, str)] if isinstance(files, list) else []
+from repowise.core.persistence import crud
+from repowise.server.deps import get_db_session, verify_api_key
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["refactoring"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+# ---------------------------------------------------------------------------
+# Response shapes (kept local — these surface only the refactoring layer)
+# ---------------------------------------------------------------------------
+
+
+class RefactoringPlanResponse(BaseModel):
+ """One ranked refactoring plan, with its open ``plan`` / ``evidence`` /
+ ``blast_radius`` dicts re-hydrated from the persisted ``*_json`` columns."""
+
+ id: str
+ refactoring_type: str
+ file_path: str
+ target_symbol: str
+ line_start: int | None = None
+ line_end: int | None = None
+ plan: dict[str, Any] = Field(default_factory=dict)
+ evidence: dict[str, Any] = Field(default_factory=dict)
+ impact_delta: float = 0.0
+ effort_bucket: str = ""
+ blast_radius: dict[str, Any] = Field(default_factory=dict)
+ confidence: str = "medium"
+ source_biomarker: str = ""
+ # The unified-rank score (higher = surface sooner). Carried so the tab can
+ # plot/sort without recomputing the blend client-side.
+ rank_score: float = 0.0
+
+
+class RefactoringTypeCount(BaseModel):
+ type: str
+ count: int
+
+
+class RefactoringSummary(BaseModel):
+ total: int
+ by_type: list[RefactoringTypeCount]
+
+
+class RefactoringTargetsResponse(BaseModel):
+ summary: RefactoringSummary
+ plans: list[RefactoringPlanResponse]
+
+
+# ---------------------------------------------------------------------------
+# Row → dataclass → response adapters
+# ---------------------------------------------------------------------------
+
+
+def _row_to_suggestion(row: Any) -> RefactoringSuggestion:
+ """Re-hydrate a persisted ORM row into the ranking dataclass.
+
+ The rank module operates on ``RefactoringSuggestion`` dataclasses (open
+ ``plan`` / ``blast_radius`` dicts); the DB stores those as ``*_json`` text.
+ We stash the row id on the instance so the ranked order can be serialized
+ back with its id intact (dataclass instances accept extra attributes)."""
+
+ def _loads(value: Any) -> dict[str, Any]:
+ if not value:
+ return {}
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+ sug = RefactoringSuggestion(
+ refactoring_type=row.refactoring_type,
+ file_path=row.file_path,
+ target_symbol=row.target_symbol,
+ line_start=row.line_start,
+ line_end=row.line_end,
+ plan=_loads(row.plan_json),
+ evidence=_loads(row.evidence_json),
+ impact_delta=row.impact_delta,
+ effort_bucket=row.effort_bucket,
+ blast_radius=_loads(row.blast_radius_json),
+ confidence=row.confidence,
+ source_biomarker=row.source_biomarker,
+ )
+ sug.id = row.id # type: ignore[attr-defined]
+ return sug
+
+
+def _to_response(sug: RefactoringSuggestion, centrality: dict[str, float]) -> RefactoringPlanResponse:
+ return RefactoringPlanResponse(
+ id=getattr(sug, "id", ""),
+ refactoring_type=sug.refactoring_type,
+ file_path=sug.file_path,
+ target_symbol=sug.target_symbol,
+ line_start=sug.line_start,
+ line_end=sug.line_end,
+ plan=sug.plan or {},
+ evidence=sug.evidence or {},
+ impact_delta=sug.impact_delta,
+ effort_bucket=sug.effort_bucket,
+ blast_radius=sug.blast_radius or {},
+ confidence=sug.confidence,
+ source_biomarker=sug.source_biomarker,
+ rank_score=round(score(sug, centrality), 4),
+ )
+
+
+async def _centrality_map(session: AsyncSession, repo_id: str) -> dict[str, float]:
+ """File-path → in-degree (importer count), the cheap dependency-centrality
+ proxy the unified rank reads. Empty when no graph metrics are materialized
+ (the rank then degrades to impact × blast × confidence)."""
+ metrics = await crud.get_graph_metrics(session, repo_id)
+ return {node_id: float(m.get("in_degree") or 0) for node_id, m in metrics.items()}
+
+
+# ---------------------------------------------------------------------------
+# Endpoints — declare the static `targets` path before the dynamic id path so
+# FastAPI matches it first.
+# ---------------------------------------------------------------------------
+
+
[email protected]("/{repo_id}/refactoring/targets", response_model=RefactoringTargetsResponse)
+async def get_refactoring_targets(
+ repo_id: str,
+ refactoring_type: str | None = Query(
+ None, description="Filter to one type: extract_class | extract_helper | move_method | break_cycle"
+ ),
+ min_confidence: str | None = Query(None, description="low | medium | high"),
+ session: AsyncSession = Depends(get_db_session),
+) -> RefactoringTargetsResponse:
+ """Ranked refactoring plans for the repo, filterable by type and confidence.
+
+ The summary ignores the *type* filter (so the per-type chips always show
+ every type's total, even while one type is selected) but does honor
+ *min_confidence* — so the summary and the plan list stay consistent under a
+ confidence filter.
+ """
+ centrality = await _centrality_map(session, repo_id)
+
+ # Summary is computed over the unfiltered-by-type set so the chips can show
+ # every type's count even while one type is selected.
+ all_rows = await crud.get_refactoring_suggestions(
+ session, repo_id, min_confidence=min_confidence
+ )
+ by_type: dict[str, int] = {}
+ for row in all_rows:
+ by_type[row.refactoring_type] = by_type.get(row.refactoring_type, 0) + 1
+ summary = RefactoringSummary(
+ total=len(all_rows),
+ by_type=[
+ RefactoringTypeCount(type=t, count=c)
+ for t, c in sorted(by_type.items(), key=lambda kv: (-kv[1], kv[0]))
+ ],
+ )
+
+ rows = (
+ all_rows
+ if refactoring_type is None
+ else [r for r in all_rows if r.refactoring_type == refactoring_type]
+ )
+ suggestions = [_row_to_suggestion(r) for r in rows]
+ ranked = rank_suggestions(suggestions, centrality=centrality)
+ return RefactoringTargetsResponse(
+ summary=summary,
+ plans=[_to_response(s, centrality) for s in ranked],
+ )
+
+
[email protected]("/{repo_id}/refactoring/{suggestion_id}", response_model=RefactoringPlanResponse)
+async def get_refactoring_plan(
+ repo_id: str,
+ suggestion_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> RefactoringPlanResponse:
+ """One plan + its blast radius detail (deep-link / drill-down target)."""
+ row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)
+ if row is None:
+ raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")
+ sug = _row_to_suggestion(row)
+ # Only this plan's file and its blast files affect its score / caller rollup,
+ # so fetch in-degree for just those rather than the whole graph_metrics table.
+ files = {sug.file_path, *(f for f in blast_files(sug) if isinstance(f, str))}
+ centrality: dict[str, float] = {}
+ for path in files:
+ degrees = await crud.get_node_degree_counts(session, repo_id, path)
+ centrality[path] = float(degrees.get("in_degree") or 0)
+ # Enrich the blast radius the same way the ranking does, so the detail view
+ # carries the caller rollup the list ranked on.
+ rank_suggestions([sug], centrality=centrality)
+ return _to_response(sug, centrality)
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 6695f3eb6..08c4a9c50 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -69,6 +69,8 @@
"./jobs/*": "./src/jobs/*.tsx",
"./blast-radius": "./src/blast-radius/index.ts",
"./blast-radius/*": "./src/blast-radius/*.tsx",
+ "./refactoring": "./src/refactoring/index.ts",
+ "./refactoring/*": "./src/refactoring/*.tsx",
"./c4": "./src/c4/index.ts",
"./c4/export": "./src/c4/export/index.ts",
"./c4/*": "./src/c4/*.tsx",
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 46ec486e1..3010a16da 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -14,6 +14,17 @@
import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
import type { RefactoringTarget } from "./refactoring-card";
+import {
+ blastFiles,
+ cutEdges,
+ cycleMembers,
+ extractClassGroups,
+ extractHelperOccurrences,
+ helperSite,
+ moveTarget,
+ type RefactoringPlan,
+} from "../refactoring/types";
+import { typeMeta } from "../refactoring/meta";
export type AiPromptFlavor =
| "generic"
@@ -1209,3 +1220,154 @@ export function buildCommitAiPrompt({
.filter((s) => s !== "")
.join("\n");
}
+
+// ─────────────────────────────────────────────────────────────────────
+// Refactoring plan prompt — hand a deterministic plan to a coding agent
+// ─────────────────────────────────────────────────────────────────────
+
+export interface BuildRefactoringPlanPromptOptions {
+ plan: RefactoringPlan;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+function planSourceLink(path: string, start: number | null, end: number | null): string {
+ if (start && end) return `\`${path}:${start}-${end}\``;
+ if (start) return `\`${path}:${start}\``;
+ return `\`${path}\``;
+}
+
+/** Render the concrete, type-specific steps the agent should carry out. The
+ * detection is already done deterministically; this is the executable plan. */
+function refactoringPlanSteps(plan: RefactoringPlan): string {
+ switch (plan.refactoring_type) {
+ case "extract_class": {
+ const groups = extractClassGroups(plan).filter(
+ (g) => g.methods.length > 0 || g.fields.length > 0,
+ );
+ const lines = groups.map((g, i) => {
+ const name = g.name ?? `NewClass${i + 1}`;
+ const methods = g.methods.length ? g.methods.join(", ") : "(none)";
+ const fields = g.fields.length ? g.fields.join(", ") : "(none)";
+ return `- **${name}** — methods: ${methods}; fields: ${fields}`;
+ });
+ return [
+ `Split \`${plan.target_symbol}\` into ${groups.length} cohesive class${
+ groups.length === 1 ? "" : "es"
+ }, one per group below. Each group's methods and the fields they touch move together:`,
+ "",
+ lines.join("\n"),
+ "",
+ "Pick a clear name for each group (the `NewClass*` placeholders are not final), keep the original class as a thin facade or update call sites, and preserve behavior.",
+ ].join("\n");
+ }
+ case "extract_helper": {
+ const occ = extractHelperOccurrences(plan);
+ const site = helperSite(plan);
+ const lines = occ.map((o) => `- ${planSourceLink(o.file, o.line_start, o.line_end)}`);
+ return [
+ `Extract the duplicated block (${occ.length} occurrence${
+ occ.length === 1 ? "" : "s"
+ }) into one shared helper${site ? ` near \`${site}\`` : ""}:`,
+ "",
+ lines.join("\n"),
+ "",
+ "Define the helper once, replace every occurrence with a call to it, and confirm the behavior is identical at each site (watch for small per-site differences that need a parameter).",
+ ].join("\n");
+ }
+ case "move_method": {
+ const mv = moveTarget(plan);
+ if (!mv) return "Move the method to the class it belongs to.";
+ return [
+ `Move \`${mv.method}\` from \`${mv.from_class}\` to \`${mv.to_class}\`${
+ mv.to_file ? ` (in \`${mv.to_file}\`)` : ""
+ }.`,
+ "",
+ "The method uses the target class's data more than its own. Move it, update both classes, and fix every call site. Only do this if the target class is legally accessible from the call sites.",
+ ].join("\n");
+ }
+ case "break_cycle": {
+ const members = cycleMembers(plan);
+ const edges = cutEdges(plan);
+ const edgeLines = edges.map((e) => `- \`${e.from}\` → \`${e.to}\``);
+ return [
+ `Break the import cycle across ${members.length} file${
+ members.length === 1 ? "" : "s"
+ } by cutting ${edges.length} edge${edges.length === 1 ? "" : "s"}:`,
+ "",
+ edgeLines.join("\n"),
+ "",
+ "For each edge, invert the dependency or introduce an abstraction/interface so the importer no longer needs the importee at module load time. Don't just move the import inside a function unless that genuinely breaks the cycle.",
+ ].join("\n");
+ }
+ default:
+ return "Apply the refactoring described above.";
+ }
+}
+
+/**
+ * Build a ready-to-paste prompt that hands a coding agent ONE deterministic
+ * refactoring plan: what to change, the concrete per-type steps, the blast
+ * radius it must keep consistent, and a completion contract. Unlike the
+ * file-level fix prompt, the plan here is already computed — the agent's job is
+ * to execute it and verify behavior, not to rediscover the smell.
+ */
+export function buildRefactoringPlanPrompt({
+ plan,
+ flavor = "generic",
+ repoName,
+}: BuildRefactoringPlanPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const meta = typeMeta(plan.refactoring_type);
+ const files = blastFiles(plan).filter((f) => f !== plan.file_path);
+
+ const constraintList = [
+ "Preserve behavior exactly — this is a refactoring, not a feature change. No public API or observable behavior should shift.",
+ "Run the project's tests (and type-checker/linter) after the change; the suite must stay green.",
+ "If, after reading the real code, the plan looks wrong or unsafe, stop and explain why instead of forcing it — the detection is static and can be a false positive.",
+ files.length > 0
+ ? `Keep these co-affected files consistent: ${files.map((f) => `\`${f}\``).join(", ")}.`
+ : null,
+ ];
+
+ const completionContract = [
+ "1. The refactored code, with each step above applied.",
+ "2. A short note on what you renamed/introduced and why.",
+ "3. Confirmation the tests pass (or the exact failures if they don't).",
+ "4. Any call sites or co-changed files you had to update.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## ${meta.label}${repoLine}`,
+ "",
+ bulletList([
+ `Target: ${planSourceLink(plan.file_path, plan.line_start, plan.line_end)}${
+ plan.target_symbol ? ` — \`${plan.target_symbol}\`` : ""
+ }`,
+ `What: ${meta.blurb}`,
+ plan.impact_delta > 0
+ ? `Recovers ~${plan.impact_delta.toFixed(2)} of health score if applied.`
+ : null,
+ plan.effort_bucket ? `Effort: ${plan.effort_bucket} bucket.` : null,
+ plan.confidence ? `Detector confidence: ${plan.confidence}.` : null,
+ ]),
+ "",
+ "## The plan",
+ "",
+ refactoringPlanSteps(plan),
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ explorationCloser(flavor, plan.file_path, "refactor"),
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
diff --git a/packages/ui/src/refactoring/index.ts b/packages/ui/src/refactoring/index.ts
new file mode 100644
index 000000000..f0a32f619
--- /dev/null
+++ b/packages/ui/src/refactoring/index.ts
@@ -0,0 +1,7 @@
+export * from "./types";
+export * from "./meta";
+export * from "./plan-detail";
+export * from "./refactoring-plan-card";
+export * from "./refactoring-quadrant";
+export * from "./refactoring-inspector";
+export * from "./refactoring-board";
diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsx
new file mode 100644
index 000000000..88ece1e38
--- /dev/null
+++ b/packages/ui/src/refactoring/meta.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import * as React from "react";
+import { ArrowRightLeft, CopyMinus, Split, Unlink } from "lucide-react";
+import type { Confidence, EffortBucket, RefactoringType } from "./types";
+
+export interface RefactoringTypeMeta {
+ label: string;
+ /** One-line description of what the refactoring does. */
+ blurb: string;
+ Icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>;
+ /** A CSS var name used for the type's accent (text + tinted backgrounds). */
+ accentVar: string;
+}
+
+export const TYPE_META: Record<string, RefactoringTypeMeta> = {
+ extract_class: {
+ label: "Extract Class",
+ blurb: "Split a low-cohesion class into focused, single-responsibility classes.",
+ Icon: Split,
+ accentVar: "--color-accent-primary",
+ },
+ extract_helper: {
+ label: "Extract Helper",
+ blurb: "Dedupe a repeated block into one shared helper.",
+ Icon: CopyMinus,
+ accentVar: "--color-success",
+ },
+ move_method: {
+ label: "Move Method",
+ blurb: "Move a method to the class it actually belongs to.",
+ Icon: ArrowRightLeft,
+ accentVar: "--color-caution",
+ },
+ break_cycle: {
+ label: "Break Cycle",
+ blurb: "Cut the minimal import edge that closes a dependency cycle.",
+ Icon: Unlink,
+ accentVar: "--color-warning",
+ },
+};
+
+const FALLBACK: RefactoringTypeMeta = {
+ label: "Refactoring",
+ blurb: "A structural improvement.",
+ Icon: Split,
+ accentVar: "--color-accent-primary",
+};
+
+export function typeMeta(type: RefactoringType | string): RefactoringTypeMeta {
+ return TYPE_META[type] ?? FALLBACK;
+}
+
+export function typeAccent(type: RefactoringType | string): string {
+ return `var(${typeMeta(type).accentVar})`;
+}
+
+export const EFFORT_LABEL: Record<EffortBucket, string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+ XL: "Extra large",
+};
+
+export const CONFIDENCE_LABEL: Record<Confidence, string> = {
+ low: "Low",
+ medium: "Medium",
+ high: "High",
+};
+
+export const CONFIDENCE_DOT: Record<Confidence, string> = {
+ high: "bg-[var(--color-success)]",
+ medium: "bg-[var(--color-caution)]",
+ low: "bg-[var(--color-text-tertiary)]",
+};
+
+/** Order types deterministically for legends and tab rows. */
+export const TYPE_ORDER: RefactoringType[] = [
+ "extract_class",
+ "extract_helper",
+ "move_method",
+ "break_cycle",
+];
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
new file mode 100644
index 000000000..9c4022647
--- /dev/null
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -0,0 +1,243 @@
+"use client";
+
+import { ArrowRight, CornerDownRight, Scissors } from "lucide-react";
+import { typeAccent } from "./meta";
+import {
+ blastFiles,
+ cutEdges,
+ cycleMembers,
+ extractClassGroups,
+ extractHelperOccurrences,
+ helperSite,
+ moveTarget,
+ type RefactoringPlan,
+} from "./types";
+
+export interface PlanDetailProps {
+ plan: RefactoringPlan;
+ /** Render a file path as a link (e.g. to the file's health drawer). */
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}
+
+function shortFile(path: string): string {
+ const parts = path.split("/");
+ return parts.length <= 2 ? path : `…/${parts.slice(-2).join("/")}`;
+}
+
+function FileRef({
+ path,
+ line,
+ fileHref,
+}: {
+ path: string;
+ line?: number | null;
+ fileHref?: PlanDetailProps["fileHref"];
+}) {
+ const label = (
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">
+ {shortFile(path)}
+ {line ? <span className="text-[var(--color-text-tertiary)]">:{line}</span> : null}
+ </span>
+ );
+ const href = fileHref?.(path, line ?? null);
+ if (!href) return label;
+ return (
+ <a
+ href={href}
+ className="font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ title={path}
+ >
+ {shortFile(path)}
+ {line ? <span className="text-[var(--color-text-tertiary)]">:{line}</span> : null}
+ </a>
+ );
+}
+
+/**
+ * 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
+ * edges. This is the "what exactly to do" — the heart of the surface.
+ */
+export function PlanDetail({ plan, fileHref }: PlanDetailProps) {
+ const accent = typeAccent(plan.refactoring_type);
+
+ if (plan.refactoring_type === "extract_class") {
+ const groups = extractClassGroups(plan).filter(
+ (g) => g.methods.length > 0 || g.fields.length > 0,
+ );
+ return (
+ <div className="space-y-3">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Split into {groups.length} cohesive group{groups.length === 1 ? "" : "s"} — each
+ group's methods travel with the fields they touch.
+ </p>
+ <div className="grid gap-2.5 sm:grid-cols-2">
+ {groups.map((g, i) => (
+ <div
+ key={i}
+ className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5"
+ >
+ <div className="mb-2 flex items-center gap-2">
+ <span
+ className="h-2 w-2 rounded-full"
+ style={{ backgroundColor: accent }}
+ aria-hidden
+ />
+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ {g.name ?? `Group ${i + 1}`}
+ </span>
+ </div>
+ {g.fields.length > 0 ? (
+ <div className="mb-1.5">
+ <span className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Fields
+ </span>
+ <div className="mt-1 flex flex-wrap gap-1">
+ {g.fields.map((f) => (
+ <code
+ key={f}
+ className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)]"
+ >
+ {f}
+ </code>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ <div>
+ <span className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Methods
+ </span>
+ <ul className="mt-1 space-y-0.5">
+ {g.methods.map((m) => (
+ <li
+ key={m}
+ className="flex items-center gap-1.5 font-mono text-[11px] text-[var(--color-text-secondary)]"
+ >
+ <CornerDownRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ {m}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (plan.refactoring_type === "extract_helper") {
+ const occ = extractHelperOccurrences(plan);
+ const site = helperSite(plan);
+ return (
+ <div className="space-y-3">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ The same block appears in {occ.length} place{occ.length === 1 ? "" : "s"}. Extract
+ it once
+ {site ? (
+ <>
+ {" "}
+ near{" "}
+ <code className="rounded bg-[var(--color-bg-elevated)] px-1 py-0.5 text-[11px] text-[var(--color-text-secondary)]">
+ {site}
+ </code>
+ </>
+ ) : null}
+ .
+ </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">
+ <FileRef path={o.file} line={o.line_start} fileHref={fileHref} />
+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ lines {o.line_start}–{o.line_end}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+ }
+
+ if (plan.refactoring_type === "move_method") {
+ const mv = moveTarget(plan);
+ if (!mv) return null;
+ return (
+ <div className="space-y-3">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ This method leans on another class's data more than its own — move it home.
+ </p>
+ <div className="flex flex-wrap items-center gap-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ From
+ </div>
+ <code className="text-xs text-[var(--color-text-secondary)]">{mv.from_class}</code>
+ </div>
+ <div className="flex flex-col items-center text-[var(--color-text-tertiary)]">
+ <code className="mb-0.5 text-[11px] text-[var(--color-text-primary)]">{mv.method}</code>
+ <ArrowRight className="h-4 w-4" style={{ color: accent }} />
+ </div>
+ <div
+ className="rounded-lg border px-3 py-2"
+ style={{ borderColor: accent, backgroundColor: `color-mix(in srgb, ${accent} 8%, transparent)` }}
+ >
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ To
+ </div>
+ <code className="text-xs text-[var(--color-text-primary)]">{mv.to_class}</code>
+ {mv.to_file ? (
+ <div className="mt-0.5">
+ <FileRef path={mv.to_file} fileHref={fileHref} />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (plan.refactoring_type === "break_cycle") {
+ const members = cycleMembers(plan);
+ const edges = cutEdges(plan);
+ return (
+ <div className="space-y-3">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {members.length} files import each other in a cycle. Cut {edges.length} edge
+ {edges.length === 1 ? "" : "s"} to break it.
+ </p>
+ <div className="space-y-2 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Cut these import edges
+ </div>
+ {edges.map((e, i) => (
+ <div key={i} className="flex items-center gap-2 text-xs">
+ <Scissors className="h-3.5 w-3.5 shrink-0" style={{ color: accent }} />
+ <FileRef path={e.from} fileHref={fileHref} />
+ <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <FileRef path={e.to} fileHref={fileHref} />
+ </div>
+ ))}
+ {members.length > 0 ? (
+ <div className="pt-1 text-[11px] text-[var(--color-text-tertiary)]">
+ Cycle: {members.map(shortFile).join(" → ")}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+ }
+
+ // Unknown type — show the raw blast files as a minimal fallback.
+ const files = blastFiles(plan);
+ return files.length ? (
+ <ul className="space-y-1">
+ {files.map((f) => (
+ <li key={f}>
+ <FileRef path={f} fileHref={fileHref} />
+ </li>
+ ))}
+ </ul>
+ ) : null;
+}
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
new file mode 100644
index 000000000..8a2da4a91
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -0,0 +1,155 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Wrench } from "lucide-react";
+import { RefactoringPlanCard } from "./refactoring-plan-card";
+import { RefactoringQuadrant } from "./refactoring-quadrant";
+import { RefactoringInspector } from "./refactoring-inspector";
+import { typeAccent, typeMeta, TYPE_ORDER } from "./meta";
+import type { RefactoringPlan, RefactoringSummary } from "./types";
+
+const PAGE_SIZE = 60;
+
+export interface RefactoringBoardProps {
+ plans: RefactoringPlan[];
+ summary?: RefactoringSummary;
+ /** Open the AI-prompt modal for a plan (host owns the modal + flavor). */
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ /** Show the priority×effort quadrant centerpiece (default true). */
+ showQuadrant?: boolean;
+ emptyTitle?: string;
+ emptyHint?: string;
+}
+
+/**
+ * The Refactoring surface. The priority×effort quadrant is the full-width
+ * centerpiece; a calm grid of compact plan cards sits below it. Clicking the
+ * quadrant or a card opens the visual inspector for that one plan. No table.
+ */
+export function RefactoringBoard({
+ plans,
+ summary,
+ onAiPrompt,
+ fileHref,
+ showQuadrant = true,
+ emptyTitle = "No refactoring plans",
+ emptyHint = "Nothing crosses the precision bar for this repo yet. Plans appear here when a class is worth splitting, a clone worth extracting, a method worth moving, or a cycle worth cutting.",
+}: RefactoringBoardProps) {
+ const [highlighted, setHighlighted] = useState<string | null>(null);
+ const [selected, setSelected] = useState<RefactoringPlan | null>(null);
+ const [inspectorOpen, setInspectorOpen] = useState(false);
+ // Render the top-ranked cards first and grow on demand — a repo can surface
+ // hundreds of plans and mounting them all at once would jank the grid.
+ const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
+
+ // Reset the window whenever the (already rank-ordered) plan set changes,
+ // e.g. on a type-filter switch, so the top is always shown first.
+ useEffect(() => {
+ setVisibleCount(PAGE_SIZE);
+ }, [plans]);
+
+ const openPlan = useCallback((plan: RefactoringPlan) => {
+ setSelected(plan);
+ setInspectorOpen(true);
+ }, []);
+
+ const pickFromQuadrant = useCallback(
+ (plan: RefactoringPlan) => {
+ setHighlighted(plan.id);
+ openPlan(plan);
+ window.setTimeout(() => setHighlighted((cur) => (cur === plan.id ? null : cur)), 2200);
+ },
+ [openPlan],
+ );
+
+ if (plans.length === 0) {
+ return (
+ <div className="mx-auto flex max-w-md flex-col items-center justify-center rounded-2xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-8 py-16 text-center">
+ <span className="mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)]">
+ <Wrench className="h-6 w-6" />
+ </span>
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">{emptyTitle}</h3>
+ <p className="mt-1.5 text-sm leading-relaxed text-[var(--color-text-tertiary)]">{emptyHint}</p>
+ </div>
+ );
+ }
+
+ const counts = new Map((summary?.by_type ?? []).map((c) => [c.type, c.count]));
+
+ return (
+ <div className="space-y-8">
+ {showQuadrant ? (
+ <section className="space-y-3">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
+ Priority × effort
+ </h2>
+ <p className="mt-0.5 max-w-2xl text-sm text-[var(--color-text-secondary)]">
+ Ranked by leverage — how depended-upon the file is, how much rides along, and the
+ health recovered. The top-left is where to start.
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {TYPE_ORDER.filter((t) => (counts.get(t) ?? 0) > 0).map((t) => {
+ const meta = typeMeta(t);
+ const { Icon } = meta;
+ return (
+ <span
+ key={t}
+ className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)]"
+ >
+ <Icon className="h-3.5 w-3.5" style={{ color: typeAccent(t) }} />
+ {meta.label}
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{counts.get(t)}</span>
+ </span>
+ );
+ })}
+ </div>
+ </div>
+ <RefactoringQuadrant plans={plans} onSelect={pickFromQuadrant} height={400} />
+ </section>
+ ) : null}
+
+ <section className="space-y-3">
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ {plans.length} plan{plans.length === 1 ? "" : "s"}
+ </h3>
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
+ {plans.slice(0, visibleCount).map((plan) => (
+ <RefactoringPlanCard
+ key={plan.id}
+ plan={plan}
+ onOpen={openPlan}
+ onAiPrompt={onAiPrompt}
+ highlighted={highlighted === plan.id}
+ />
+ ))}
+ </div>
+ {plans.length > visibleCount ? (
+ <div className="flex justify-center pt-1">
+ <button
+ type="button"
+ onClick={() => setVisibleCount((n) => n + PAGE_SIZE)}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-4 py-2 text-sm font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)]"
+ >
+ Show {Math.min(PAGE_SIZE, plans.length - visibleCount)} more
+ <span className="text-[var(--color-text-tertiary)]">
+ · {plans.length - visibleCount} left
+ </span>
+ </button>
+ </div>
+ ) : null}
+ </section>
+
+ <RefactoringInspector
+ plan={selected}
+ open={inspectorOpen}
+ onOpenChange={setInspectorOpen}
+ onAiPrompt={onAiPrompt}
+ fileHref={fileHref}
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-inspector.tsx b/packages/ui/src/refactoring/refactoring-inspector.tsx
new file mode 100644
index 000000000..90bac51eb
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-inspector.tsx
@@ -0,0 +1,208 @@
+"use client";
+
+import { Layers, Sparkles } from "lucide-react";
+import { Sheet, SheetContent, SheetHeader, SheetTitle } from "../ui/sheet";
+import { PlanDetail } from "./plan-detail";
+import { CONFIDENCE_LABEL, EFFORT_LABEL, typeAccent, typeMeta } from "./meta";
+import {
+ blastCount,
+ blastFiles,
+ type Confidence,
+ type EffortBucket,
+ type RefactoringPlan,
+} from "./types";
+
+export interface RefactoringInspectorProps {
+ plan: RefactoringPlan | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}
+
+const EVIDENCE_LABELS: Record<string, string> = {
+ lcom4: "LCOM4",
+ method_count: "Methods",
+ field_count: "Fields",
+ wmc: "WMC",
+ occurrence_count: "Occurrences",
+ duplicated_lines: "Duplicated lines",
+ co_change_count: "Co-changes",
+ foreign_calls: "Calls to target",
+ own_calls: "Calls to own class",
+ own_distance: "Distance to own",
+ target_distance: "Distance to target",
+ cycle_size: "Cycle size",
+ edge_count: "Edges in cycle",
+ cut_count: "Edges to cut",
+};
+
+function evidenceRows(plan: RefactoringPlan): { label: string; value: string }[] {
+ const rows: { label: string; value: string }[] = [];
+ for (const [key, label] of Object.entries(EVIDENCE_LABELS)) {
+ const v = plan.evidence?.[key];
+ if (typeof v === "number" && Number.isFinite(v)) {
+ rows.push({ label, value: Number.isInteger(v) ? String(v) : v.toFixed(2) });
+ }
+ }
+ return rows;
+}
+
+/**
+ * The slide-over that renders one plan visually: the concrete per-type plan,
+ * the evidence behind it, and the blast radius. Mounted only for the selected
+ * plan, so the heavy visual cost is paid once, on demand.
+ */
+export function RefactoringInspector({
+ plan,
+ open,
+ onOpenChange,
+ onAiPrompt,
+ fileHref,
+}: RefactoringInspectorProps) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ className="w-full gap-0 overflow-y-auto p-0 sm:max-w-xl"
+ >
+ {plan ? <InspectorBody plan={plan} onAiPrompt={onAiPrompt} fileHref={fileHref} /> : null}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function InspectorBody({
+ plan,
+ onAiPrompt,
+ fileHref,
+}: {
+ plan: RefactoringPlan;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}) {
+ const meta = typeMeta(plan.refactoring_type);
+ const accent = typeAccent(plan.refactoring_type);
+ const { Icon } = meta;
+ const effort = (plan.effort_bucket || "M") as EffortBucket;
+ const confidence = (plan.confidence || "medium") as Confidence;
+ const evidence = evidenceRows(plan);
+ const blast = blastFiles(plan).filter((f) => f !== plan.file_path);
+ const blastN = blastCount(plan);
+
+ return (
+ <>
+ <SheetHeader className="border-b border-[var(--color-border-default)] px-6 py-5 pr-12">
+ <SheetTitle className="flex items-center gap-3 text-base">
+ <span
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl"
+ style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}
+ >
+ <Icon className="h-[18px] w-[18px]" />
+ </span>
+ <span className="min-w-0">
+ <span className="block font-semibold text-[var(--color-text-primary)]">{meta.label}</span>
+ <code className="block truncate text-xs font-normal text-[var(--color-text-secondary)]">
+ {plan.target_symbol}
+ </code>
+ </span>
+ </SheetTitle>
+ </SheetHeader>
+
+ <div className="space-y-6 px-6 py-5">
+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">{meta.blurb}</p>
+
+ {/* Signal chips */}
+ <div className="flex flex-wrap gap-2">
+ <Chip label="Effort" value={EFFORT_LABEL[effort]} />
+ <Chip label="Confidence" value={CONFIDENCE_LABEL[confidence]} />
+ {blastN > 0 ? <Chip label="Touches" value={`${blastN} file${blastN === 1 ? "" : "s"}`} /> : null}
+ {plan.impact_delta > 0 ? <Chip label="Recovers" value={`+${plan.impact_delta.toFixed(2)}`} /> : null}
+ </div>
+
+ {/* The visual plan */}
+ <section>
+ <h4 className="mb-2.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ The plan
+ </h4>
+ <PlanDetail plan={plan} fileHref={fileHref} />
+ </section>
+
+ {/* Evidence */}
+ {evidence.length > 0 ? (
+ <section>
+ <h4 className="mb-2.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Why this was flagged
+ </h4>
+ <dl className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ {evidence.map((row) => (
+ <div
+ key={row.label}
+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2"
+ >
+ <dt className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {row.label}
+ </dt>
+ <dd className="mt-0.5 text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {row.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ ) : null}
+
+ {/* Blast radius */}
+ {blast.length > 0 ? (
+ <section>
+ <h4 className="mb-2.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <Layers className="h-3.5 w-3.5" />
+ Also affected
+ </h4>
+ <ul className="space-y-1">
+ {blast.map((f) => {
+ const href = fileHref?.(f, null);
+ return (
+ <li key={f}>
+ {href ? (
+ <a
+ href={href}
+ className="font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {f}
+ </a>
+ ) : (
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">{f}</span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ ) : null}
+ </div>
+
+ {onAiPrompt ? (
+ <div className="sticky bottom-0 mt-auto border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-6 py-4">
+ <button
+ type="button"
+ onClick={() => onAiPrompt(plan)}
+ className="inline-flex items-center gap-2 rounded-lg bg-[var(--color-accent-primary)] px-3.5 py-2 text-sm font-semibold text-[var(--color-bg-surface)] transition-opacity hover:opacity-90"
+ >
+ <Sparkles className="h-4 w-4" />
+ Get AI prompt
+ </button>
+ </div>
+ ) : null}
+ </>
+ );
+}
+
+function Chip({ label, value }: { label: string; value: string }) {
+ return (
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1 text-xs">
+ <span className="text-[var(--color-text-tertiary)]">{label}</span>
+ <span className="font-medium text-[var(--color-text-primary)]">{value}</span>
+ </span>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-plan-card.tsx b/packages/ui/src/refactoring/refactoring-plan-card.tsx
new file mode 100644
index 000000000..c7fd1321b
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-plan-card.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { Layers, Sparkles } from "lucide-react";
+import { CONFIDENCE_DOT, CONFIDENCE_LABEL, EFFORT_LABEL, typeAccent, typeMeta } from "./meta";
+import {
+ blastCount,
+ planSynopsis,
+ type Confidence,
+ type EffortBucket,
+ type RefactoringPlan,
+} from "./types";
+
+export interface RefactoringPlanCardProps {
+ plan: RefactoringPlan;
+ /** Open the visual plan inspector for this plan. */
+ onOpen?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Open the AI-prompt modal for this plan. */
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Flash-highlight (e.g. after a quadrant dot click scrolled to it). */
+ highlighted?: boolean;
+}
+
+function shortFile(path: string): string {
+ const parts = path.split("/");
+ return parts.length <= 3 ? path : `…/${parts.slice(-3).join("/")}`;
+}
+
+/**
+ * A compact, clickable plan card. Deliberately light — the heavy visual lives
+ * in the inspector that opens on click — so a long grid stays performant.
+ */
+export function RefactoringPlanCard({
+ plan,
+ onOpen,
+ onAiPrompt,
+ highlighted = false,
+}: RefactoringPlanCardProps) {
+ const meta = typeMeta(plan.refactoring_type);
+ const accent = typeAccent(plan.refactoring_type);
+ const { Icon } = meta;
+ const blast = blastCount(plan);
+ const effort = (plan.effort_bucket || "M") as EffortBucket;
+ const confidence = (plan.confidence || "medium") as Confidence;
+
+ return (
+ <article
+ data-refactoring-plan={plan.id}
+ className={`group relative flex flex-col rounded-2xl border bg-[var(--color-bg-surface)] transition-all ${
+ highlighted
+ ? "border-[var(--color-accent-primary)] ring-1 ring-[var(--color-accent-primary)]/30"
+ : "border-[var(--color-border-default)] hover:border-[var(--color-border-strong)] hover:shadow-sm"
+ }`}
+ >
+ <button
+ type="button"
+ onClick={onOpen ? () => onOpen(plan) : undefined}
+ className="flex flex-1 flex-col gap-3 p-4 text-left"
+ disabled={!onOpen}
+ aria-label={`Open ${meta.label} plan for ${plan.target_symbol}`}
+ >
+ <div className="flex items-start gap-3">
+ <span
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"
+ style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}
+ >
+ <Icon className="h-4 w-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="text-[13px] font-semibold text-[var(--color-text-primary)]">
+ {meta.label}
+ </span>
+ <span
+ className="inline-flex items-center gap-1 text-[10px] text-[var(--color-text-tertiary)]"
+ title={`Detector confidence: ${CONFIDENCE_LABEL[confidence]}`}
+ >
+ <span className={`h-1.5 w-1.5 rounded-full ${CONFIDENCE_DOT[confidence]}`} />
+ {CONFIDENCE_LABEL[confidence]}
+ </span>
+ </div>
+ <p className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]">
+ {planSynopsis(plan)}
+ </p>
+ </div>
+ </div>
+
+ {plan.target_symbol ? (
+ <code className="block truncate text-[11px] text-[var(--color-text-secondary)]">
+ {plan.target_symbol}
+ </code>
+ ) : null}
+ <span
+ className="truncate font-mono text-[11px] text-[var(--color-text-tertiary)]"
+ title={plan.file_path}
+ >
+ {shortFile(plan.file_path)}
+ </span>
+
+ <div className="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1.5 pt-1 text-[11px] text-[var(--color-text-tertiary)]">
+ <span title={`Effort: ${EFFORT_LABEL[effort]}`} className="inline-flex items-center gap-1">
+ <span className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 font-medium tabular-nums text-[var(--color-text-secondary)]">
+ {effort}
+ </span>
+ </span>
+ {blast > 0 ? (
+ <span className="inline-flex items-center gap-1" title="Files this refactoring touches">
+ <Layers className="h-3.5 w-3.5" />
+ {blast}
+ </span>
+ ) : null}
+ {plan.impact_delta > 0 ? (
+ <span className="tabular-nums" title="Health recovered if applied">
+ +{plan.impact_delta.toFixed(1)}
+ </span>
+ ) : null}
+ </div>
+ </button>
+
+ {onAiPrompt ? (
+ <div className="border-t border-[var(--color-border-default)] px-4 py-2">
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onAiPrompt(plan);
+ }}
+ className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-semibold text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-muted)]"
+ title="Open a ready-to-paste prompt for your AI coding agent"
+ >
+ <Sparkles className="h-3.5 w-3.5" />
+ AI prompt
+ </button>
+ </div>
+ ) : null}
+ </article>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-quadrant.tsx b/packages/ui/src/refactoring/refactoring-quadrant.tsx
new file mode 100644
index 000000000..650e393ab
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-quadrant.tsx
@@ -0,0 +1,145 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { typeAccent, typeMeta } from "./meta";
+import type { EffortBucket, RefactoringPlan } from "./types";
+
+export interface RefactoringQuadrantProps {
+ plans: RefactoringPlan[];
+ onSelect?: (plan: RefactoringPlan) => void;
+ height?: number;
+}
+
+const EFFORT_X: Record<EffortBucket, number> = { S: 13, M: 38, L: 63, XL: 87 };
+
+// Plot at most this many dots (the highest-ranked) so hover stays smooth on
+// repos that surface hundreds of plans. The list below the quadrant still
+// paginates through every plan.
+const MAX_DOTS = 120;
+
+/**
+ * Priority × effort scatter — the surface's centerpiece. Y is the unified rank
+ * score (so graph-native plans with zero recovered health still place by
+ * centrality + blast), X is the effort bucket. Dots are colored by refactoring
+ * type. The top-left is the sweet spot: high priority, low effort.
+ */
+export function RefactoringQuadrant({ plans, onSelect, height = 400 }: RefactoringQuadrantProps) {
+ const [hovered, setHovered] = useState<RefactoringPlan | null>(null);
+ const scored = useMemo(() => plans.filter((p) => p.rank_score > 0), [plans]);
+ const data = useMemo(() => scored.slice(0, MAX_DOTS), [scored]);
+ const capped = scored.length > MAX_DOTS;
+
+ if (data.length === 0) {
+ return (
+ <div className="flex items-center justify-center rounded-2xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-10 text-sm text-[var(--color-text-tertiary)]" style={{ minHeight: height }}>
+ No plans to plot yet.
+ </div>
+ );
+ }
+
+ const W = 1100;
+ const H = height;
+ const padL = 48;
+ const padR = 48;
+ const padT = 34;
+ const padB = 48;
+ const plotW = W - padL - padR;
+ const plotH = H - padT - padB;
+ const maxScore = Math.max(...data.map((d) => d.rank_score), 1);
+ const minScore = Math.min(...data.map((d) => d.rank_score));
+ const flat = maxScore === minScore;
+
+ const xScale = (pct: number) => padL + (pct / 100) * plotW;
+ // Keep dots off the very top/bottom edges (7% inset each side).
+ const yScale = (s: number) =>
+ flat
+ ? padT + plotH / 2
+ : padT + plotH * 0.07 + ((maxScore - s) / (maxScore - minScore)) * plotH * 0.86;
+
+ const midX = xScale(50);
+ const midY = padT + plotH / 2;
+
+ const jitter = (s: string) => {
+ let h = 0;
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
+ return ((h % 16) - 8) * 1.6;
+ };
+
+ return (
+ <div className="rounded-2xl border border-[var(--color-border-default)] bg-gradient-to-br from-[var(--color-bg-surface)] to-[var(--color-bg-elevated)]/30 p-2 text-[var(--color-text-primary)]">
+ {capped ? (
+ <p className="px-2 pt-1 text-[11px] text-[var(--color-text-tertiary)]">
+ Showing the top {MAX_DOTS} of {scored.length} by priority
+ </p>
+ ) : null}
+ <div className="relative">
+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Priority versus effort scatter plot" className="overflow-visible">
+ {/* quadrant tints — top-left (high priority / low effort) is the sweet spot */}
+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/[0.06]" />
+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-caution)]/[0.04]" />
+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-text-tertiary)]/[0.03]" />
+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-text-tertiary)]/[0.03]" />
+
+ {/* frame + mid gridlines */}
+ <line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.14} />
+ <line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.14} />
+ <line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.07} strokeDasharray="4 5" />
+ <line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.07} strokeDasharray="4 5" />
+
+ {/* corner labels */}
+ <text x={padL + 8} y={padT + 16} fontSize={13} fontWeight={600} fill="currentColor" opacity={0.55}>Do first</text>
+ <text x={W - padR - 8} y={padT + 16} textAnchor="end" fontSize={13} fontWeight={600} fill="currentColor" opacity={0.4}>Big bets</text>
+ <text x={padL + 8} y={H - padB - 8} fontSize={12} fill="currentColor" opacity={0.35}>Nice to have</text>
+ <text x={W - padR - 8} y={H - padB - 8} textAnchor="end" fontSize={12} fill="currentColor" opacity={0.3}>Heavy lifts</text>
+
+ {/* axes */}
+ {(["S", "M", "L", "XL"] as EffortBucket[]).map((b) => (
+ <text key={b} x={xScale(EFFORT_X[b])} y={H - padB + 20} fontSize={12} textAnchor="middle" fill="currentColor" opacity={0.5}>
+ {b}
+ </text>
+ ))}
+ <text x={W / 2} y={H - 6} fontSize={12} textAnchor="middle" fill="currentColor" opacity={0.45}>Effort →</text>
+ <text x={14} y={H / 2} fontSize={12} textAnchor="middle" fill="currentColor" opacity={0.45} transform={`rotate(-90 14 ${H / 2})`}>Priority →</text>
+
+ {data.map((p) => {
+ const cx = xScale(EFFORT_X[(p.effort_bucket || "M") as EffortBucket]) + jitter(p.id);
+ const cy = yScale(p.rank_score);
+ const isHovered = hovered?.id === p.id;
+ const accent = typeAccent(p.refactoring_type);
+ return (
+ <circle
+ key={p.id}
+ cx={cx}
+ cy={cy}
+ r={isHovered ? 9 : 6.5}
+ fill={accent}
+ fillOpacity={isHovered ? 0.95 : 0.72}
+ stroke={isHovered ? "var(--color-bg-surface)" : "none"}
+ strokeWidth={2}
+ className={onSelect ? "cursor-pointer transition-all" : "transition-all"}
+ onMouseEnter={() => setHovered(p)}
+ onMouseLeave={() => setHovered(null)}
+ onClick={onSelect ? () => onSelect(p) : undefined}
+ >
+ <title>{`${typeMeta(p.refactoring_type).label} · ${p.target_symbol}\n${p.effort_bucket} effort · priority ${p.rank_score.toFixed(2)}`}</title>
+ </circle>
+ );
+ })}
+ </svg>
+ {hovered ? (
+ <div className="pointer-events-none absolute left-3 top-3 max-w-[60%] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 shadow-md">
+ <div className="flex items-center gap-1.5">
+ <span className="h-2 w-2 rounded-full" style={{ backgroundColor: typeAccent(hovered.refactoring_type) }} />
+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ {typeMeta(hovered.refactoring_type).label}
+ </span>
+ </div>
+ <code className="mt-0.5 block truncate text-[11px] text-[var(--color-text-tertiary)]">
+ {hovered.target_symbol}
+ </code>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
new file mode 100644
index 000000000..628d8fe2f
--- /dev/null
+++ b/packages/ui/src/refactoring/types.ts
@@ -0,0 +1,180 @@
+/**
+ * Shared types for the refactoring surface.
+ *
+ * These mirror the `/api/repos/{id}/refactoring/*` responses. The `plan`,
+ * `evidence`, and `blast_radius` payloads are open per-type dicts (the backend
+ * stores them as JSON); the typed accessors below describe each refactoring
+ * type's shape so the plan renderer can read them without `any`.
+ */
+
+export type RefactoringType =
+ | "extract_class"
+ | "extract_helper"
+ | "move_method"
+ | "break_cycle";
+
+export type EffortBucket = "S" | "M" | "L" | "XL";
+export type Confidence = "low" | "medium" | "high";
+
+export interface RefactoringPlan {
+ id: string;
+ refactoring_type: RefactoringType | string;
+ file_path: string;
+ target_symbol: string;
+ line_start: number | null;
+ line_end: number | null;
+ plan: Record<string, unknown>;
+ evidence: Record<string, unknown>;
+ impact_delta: number;
+ effort_bucket: EffortBucket | string;
+ blast_radius: Record<string, unknown>;
+ confidence: Confidence | string;
+ source_biomarker: string;
+ rank_score: number;
+}
+
+export interface RefactoringTypeCount {
+ type: string;
+ count: number;
+}
+
+export interface RefactoringSummary {
+ total: number;
+ by_type: RefactoringTypeCount[];
+}
+
+export interface RefactoringTargets {
+ summary: RefactoringSummary;
+ plans: RefactoringPlan[];
+}
+
+// ── Per-type plan shapes (the open `plan` dict, read defensively) ──────────
+
+export interface ExtractClassGroup {
+ name: string | null;
+ methods: string[];
+ fields: string[];
+}
+
+export interface ExtractHelperOccurrence {
+ file: string;
+ line_start: number;
+ line_end: number;
+}
+
+export interface CutEdge {
+ from: string;
+ to: string;
+}
+
+export function extractClassGroups(plan: RefactoringPlan): ExtractClassGroup[] {
+ const groups = plan.plan?.groups;
+ if (!Array.isArray(groups)) return [];
+ return groups.map((g) => {
+ const rec = (g ?? {}) as Record<string, unknown>;
+ return {
+ name: typeof rec.name === "string" ? rec.name : null,
+ methods: Array.isArray(rec.methods) ? (rec.methods as string[]) : [],
+ fields: Array.isArray(rec.fields) ? (rec.fields as string[]) : [],
+ };
+ });
+}
+
+export function extractHelperOccurrences(plan: RefactoringPlan): ExtractHelperOccurrence[] {
+ const occ = plan.plan?.occurrences;
+ if (!Array.isArray(occ)) return [];
+ return occ.map((o) => {
+ const rec = (o ?? {}) as Record<string, unknown>;
+ return {
+ file: String(rec.file ?? ""),
+ line_start: Number(rec.line_start ?? 0),
+ line_end: Number(rec.line_end ?? 0),
+ };
+ });
+}
+
+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;
+}
+
+export interface MoveTarget {
+ method: string;
+ from_class: string;
+ to_class: string;
+ to_file: string | null;
+}
+
+export function moveTarget(plan: RefactoringPlan): MoveTarget | null {
+ const p = plan.plan as Record<string, unknown>;
+ if (!p || typeof p.method !== "string") return null;
+ return {
+ method: p.method,
+ from_class: String(p.from_class ?? ""),
+ to_class: String(p.to_class ?? ""),
+ to_file: typeof p.to_file === "string" ? p.to_file : null,
+ };
+}
+
+export function cycleMembers(plan: RefactoringPlan): string[] {
+ const cycle = plan.plan?.cycle;
+ return Array.isArray(cycle) ? (cycle as string[]) : [];
+}
+
+export function cutEdges(plan: RefactoringPlan): CutEdge[] {
+ const edges = plan.plan?.cut_edges;
+ if (!Array.isArray(edges)) return [];
+ return edges.map((e) => {
+ const rec = (e ?? {}) as Record<string, unknown>;
+ return { from: String(rec.from ?? ""), to: String(rec.to ?? "") };
+ });
+}
+
+/** A one-line synopsis for the compact card — what the plan does, at a glance. */
+export function planSynopsis(plan: RefactoringPlan): string {
+ switch (plan.refactoring_type) {
+ case "extract_class": {
+ const n = extractClassGroups(plan).filter(
+ (g) => g.methods.length > 0 || g.fields.length > 0,
+ ).length;
+ return `Split into ${n} cohesive class${n === 1 ? "" : "es"}`;
+ }
+ case "extract_helper": {
+ const occ = extractHelperOccurrences(plan);
+ const lines = Number(plan.evidence?.duplicated_lines ?? 0);
+ return `${occ.length} duplicate${occ.length === 1 ? "" : "s"}${
+ lines ? ` · ${lines} lines` : ""
+ }`;
+ }
+ case "move_method": {
+ const mv = moveTarget(plan);
+ return mv ? `${mv.from_class} → ${mv.to_class}` : "Move method";
+ }
+ case "break_cycle": {
+ const members = cycleMembers(plan).length;
+ const edges = cutEdges(plan).length;
+ return `${members} files · cut ${edges} edge${edges === 1 ? "" : "s"}`;
+ }
+ default:
+ return "";
+ }
+}
+
+/** The files this refactoring drags along, read from whichever blast-radius
+ * shape the type carries. */
+export function blastFiles(plan: RefactoringPlan): string[] {
+ const files = plan.blast_radius?.files;
+ return Array.isArray(files) ? (files as string[]) : [];
+}
+
+export function blastCount(plan: RefactoringPlan): number {
+ const br = plan.blast_radius ?? {};
+ for (const key of ["file_count", "dependents_count", "callers"] as const) {
+ const v = br[key];
+ if (typeof v === "number" && v) return v;
+ }
+ return blastFiles(plan).length;
+}
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
new file mode 100644
index 000000000..2d9378d76
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+/**
+ * Refactoring — `/repos/[id]/refactoring`.
+ *
+ * A first-class surface for the deterministic refactoring plans the health
+ * pass writes (Extract Class, Extract Helper, Move Method, Break Cycle). The
+ * card board is the primary view; a priority×effort quadrant heads it. Type
+ * filters are URL-synced via `?type=` (nuqs), mirroring the architecture view.
+ */
+
+import { use, useCallback, useMemo, useState } from "react";
+import useSWR from "swr";
+import { parseAsStringLiteral, useQueryState } from "nuqs";
+import { Wrench, RotateCw } from "lucide-react";
+import { PageShell } from "@repowise-dev/ui/shared/page-shell";
+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { RefactoringBoard, TYPE_ORDER, typeMeta } from "@repowise-dev/ui/refactoring";
+import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+import { AiPromptModal, buildRefactoringPlanPrompt } from "@repowise-dev/ui/health";
+import { getRefactoringTargets } from "@/lib/api/refactoring";
+
+const TYPE_VALUES = ["all", ...TYPE_ORDER] as const;
+type TypeFilter = (typeof TYPE_VALUES)[number];
+
+export default function RefactoringPage({ params }: { params: Promise<{ id: string }> }) {
+ const { id: repoId } = use(params);
+ const [type, setType] = useQueryState(
+ "type",
+ parseAsStringLiteral(TYPE_VALUES).withDefault("all"),
+ );
+
+ const { data, error, isLoading, mutate } = useSWR<RefactoringTargets>(
+ `refactoring:${repoId}`,
+ () => getRefactoringTargets(repoId),
+ { revalidateOnFocus: false },
+ );
+
+ const filtered = useMemo(() => {
+ const plans = data?.plans ?? [];
+ return type === "all" ? plans : plans.filter((p) => p.refactoring_type === type);
+ }, [data?.plans, type]);
+
+ const prefix = `/repos/${repoId}`;
+ const fileHref = (path: string) => fileEntityPath(prefix, path);
+
+ // AI-prompt modal (flavor picker + copy) — same UX as the health surface.
+ const [promptPlan, setPromptPlan] = useState<RefactoringPlan | null>(null);
+ const onAiPrompt = useCallback((plan: RefactoringPlan) => setPromptPlan(plan), []);
+
+ const counts = new Map((data?.summary.by_type ?? []).map((c) => [c.type, c.count]));
+ const tabs = [
+ { id: "all" as const, label: "All", badge: data?.summary.total },
+ ...TYPE_ORDER.map((t) => ({
+ id: t,
+ label: typeMeta(t).label,
+ badge: counts.get(t) ?? 0,
+ })),
+ ].filter((t) => t.id === "all" || (t.badge ?? 0) > 0);
+
+ return (
+ <PageShell
+ title="Refactoring"
+ icon={<Wrench className="h-5 w-5 text-[var(--color-accent-primary)]" />}
+ description="Concrete, ranked refactoring plans — split, dedupe, move, and decouple. Copy any plan straight to your coding agent."
+ actions={
+ <button
+ type="button"
+ onClick={() => void mutate()}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)]"
+ >
+ <RotateCw className="h-3.5 w-3.5" />
+ Refresh
+ </button>
+ }
+ >
+ <div className="space-y-6">
+ <ViewTabs
+ tabs={tabs}
+ value={type}
+ onValueChange={(id) => void setType(id as TypeFilter)}
+ />
+
+ {error ? (
+ <div className="rounded-2xl border border-[var(--color-error)]/30 bg-[var(--color-error)]/5 p-6 text-sm text-[var(--color-text-secondary)]">
+ Couldn&apos;t load refactoring plans. The repo may not be indexed yet, or the API is
+ unreachable.
+ </div>
+ ) : isLoading ? (
+ <div className="grid gap-5 xl:grid-cols-2">
+ {[0, 1, 2, 3].map((i) => (
+ <div
+ key={i}
+ className="h-56 animate-pulse rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ />
+ ))}
+ </div>
+ ) : (
+ <RefactoringBoard
+ plans={filtered}
+ summary={data?.summary}
+ onAiPrompt={onAiPrompt}
+ fileHref={fileHref}
+ />
+ )}
+ </div>
+
+ <AiPromptModal
+ open={promptPlan !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptPlan(null);
+ }}
+ getPrompt={
+ promptPlan
+ ? (flavor) => buildRefactoringPlanPrompt({ plan: promptPlan, flavor })
+ : null
+ }
+ filePath={promptPlan?.file_path ?? null}
+ title="AI refactoring prompt"
+ description="A ready-to-paste plan that hands your AI coding agent the exact steps, the blast radius to keep consistent, and a completion contract."
+ />
+ </PageShell>
+ );
+}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index 47dbbce40..a2b819a08 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -25,6 +25,7 @@ import {
ShieldCheck,
Users,
Waypoints,
+ Wrench,
} from "lucide-react";
export interface NavItem {
@@ -63,6 +64,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {
{ label: "Architecture", href: `${base}/architecture`, icon: Boxes },
{ label: "Knowledge Graph", href: `${base}/knowledge-graph`, icon: Waypoints },
{ label: "Code Health", href: `${base}/code-health`, icon: HeartPulse },
+ { label: "Refactoring", href: `${base}/refactoring`, icon: Wrench },
],
},
{
diff --git a/packages/web/src/lib/api/refactoring.ts b/packages/web/src/lib/api/refactoring.ts
new file mode 100644
index 000000000..f96f493a8
--- /dev/null
+++ b/packages/web/src/lib/api/refactoring.ts
@@ -0,0 +1,29 @@
+/**
+ * REST client for the refactoring endpoints.
+ * Backend: packages/server/src/repowise/server/routers/refactoring.py
+ */
+
+import { apiGet } from "./client";
+import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+
+export interface RefactoringTargetsParams {
+ refactoringType?: string;
+ minConfidence?: string;
+}
+
+export async function getRefactoringTargets(
+ repoId: string,
+ params: RefactoringTargetsParams = {},
+): Promise<RefactoringTargets> {
+ return apiGet<RefactoringTargets>(`/api/repos/${repoId}/refactoring/targets`, {
+ refactoring_type: params.refactoringType,
+ min_confidence: params.minConfidence,
+ });
+}
+
+export async function getRefactoringPlan(
+ repoId: string,
+ suggestionId: string,
+): Promise<RefactoringPlan> {
+ return apiGet<RefactoringPlan>(`/api/repos/${repoId}/refactoring/${suggestionId}`);
+}
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index d7b5a78be..b269862b2 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -42,6 +42,7 @@ def _create_test_app():
overview,
owners,
pages,
+ refactoring,
repos,
search,
symbols,
@@ -86,6 +87,7 @@ def _create_test_app():
app.include_router(decisions.router)
app.include_router(external_systems.router)
app.include_router(overview.router)
+ app.include_router(refactoring.router)
return app
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
new file mode 100644
index 000000000..baf89212a
--- /dev/null
+++ b/tests/unit/server/test_refactoring.py
@@ -0,0 +1,227 @@
+"""HTTP-level tests for /api/repos/{repo_id}/refactoring/{targets,:id}."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+
+from httpx import AsyncClient
+
+from repowise.core.persistence import (
+ batch_upsert_graph_edges,
+ batch_upsert_graph_nodes,
+)
+from repowise.core.persistence import crud
+
+
+async def create_test_repo(client: AsyncClient) -> dict:
+ repo_dir = Path(tempfile.mkdtemp()) / "test-repo"
+ repo_dir.mkdir(exist_ok=True)
+ (repo_dir / ".git").mkdir(exist_ok=True)
+ resp = await client.post(
+ "/api/repos",
+ json={
+ "name": "test-repo",
+ "local_path": str(repo_dir),
+ "url": "https://github.com/example/test-repo",
+ },
+ )
+ assert resp.status_code == 201
+ return resp.json()
+
+
+async def _seed(client: AsyncClient, app) -> str:
+ """A repo + a tiny graph (for centrality) + four refactoring plans, one of
+ each type. ``hub.py`` is imported by two files so it is the central one."""
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+
+ async with app.state.session_factory() as session:
+ await batch_upsert_graph_nodes(session, repo_id, [
+ {"node_id": "pkg/hub.py", "node_type": "file", "language": "python", "symbol_count": 9},
+ {"node_id": "pkg/leaf.py", "node_type": "file", "language": "python", "symbol_count": 3},
+ {"node_id": "pkg/a.py", "node_type": "file", "language": "python", "symbol_count": 2},
+ {"node_id": "pkg/b.py", "node_type": "file", "language": "python", "symbol_count": 2},
+ ])
+ # hub.py has in-degree 2 (a, b import it); leaf.py has in-degree 0.
+ await batch_upsert_graph_edges(session, repo_id, [
+ {"source_node_id": "pkg/a.py", "target_node_id": "pkg/hub.py", "edge_type": "imports"},
+ {"source_node_id": "pkg/b.py", "target_node_id": "pkg/hub.py", "edge_type": "imports"},
+ ])
+ await crud.save_refactoring_suggestions(session, repo_id, [
+ {
+ "refactoring_type": "extract_class",
+ "file_path": "pkg/leaf.py",
+ "target_symbol": "GodClass",
+ "line_start": 1,
+ "line_end": 200,
+ "plan": {"groups": [
+ {"name": None, "methods": ["a", "b"], "fields": ["x"]},
+ {"name": None, "methods": ["c", "d"], "fields": ["y"]},
+ ]},
+ "evidence": {"lcom4": 2, "method_count": 6, "field_count": 2, "wmc": 40},
+ "impact_delta": 2.5,
+ "effort_bucket": "L",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "high",
+ "source_biomarker": "low_cohesion",
+ },
+ {
+ "refactoring_type": "extract_helper",
+ "file_path": "pkg/hub.py",
+ "target_symbol": "dup_block",
+ "line_start": 10,
+ "line_end": 30,
+ "plan": {
+ "occurrences": [
+ {"file": "pkg/hub.py", "line_start": 10, "line_end": 30},
+ {"file": "pkg/a.py", "line_start": 5, "line_end": 25},
+ ],
+ "suggested_site": {"module": "pkg", "directory": "pkg"},
+ "duplicated_lines": 20,
+ },
+ "evidence": {"occurrence_count": 2, "duplicated_lines": 20, "co_change_count": 4},
+ "impact_delta": 0.6,
+ "effort_bucket": "M",
+ "blast_radius": {"files": ["pkg/hub.py", "pkg/a.py"], "file_count": 2, "co_change_count": 4},
+ "confidence": "high",
+ "source_biomarker": "dry_violation",
+ },
+ {
+ "refactoring_type": "move_method",
+ "file_path": "pkg/a.py",
+ "target_symbol": "Helper.do_work",
+ "line_start": 40,
+ "line_end": 60,
+ "plan": {"method": "do_work", "from_class": "Helper", "to_class": "Worker", "to_file": "pkg/b.py"},
+ "evidence": {"foreign_calls": 3, "own_calls": 0, "own_distance": 0.95, "target_distance": 0.4},
+ "impact_delta": 0.0,
+ "effort_bucket": "S",
+ "blast_radius": {"callers": 1, "files": ["pkg/a.py", "pkg/b.py"]},
+ "confidence": "medium",
+ "source_biomarker": "",
+ },
+ {
+ "refactoring_type": "break_cycle",
+ "file_path": "pkg/a.py",
+ "target_symbol": "pkg/a.py↔pkg/b.py",
+ "line_start": None,
+ "line_end": None,
+ "plan": {"cycle": ["pkg/a.py", "pkg/b.py"], "cut_edges": [{"from": "pkg/a.py", "to": "pkg/b.py"}]},
+ "evidence": {"cycle_size": 2, "edge_count": 2, "cut_count": 1},
+ "impact_delta": 0.0,
+ "effort_bucket": "M",
+ "blast_radius": {"files": ["pkg/a.py", "pkg/b.py"], "file_count": 2},
+ "confidence": "medium",
+ "source_biomarker": "",
+ },
+ ])
+ await session.commit()
+ return repo_id
+
+
+async def test_targets_returns_ranked_plans_and_summary(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ resp = await client.get(f"/api/repos/{repo_id}/refactoring/targets")
+ assert resp.status_code == 200
+ body = resp.json()
+
+ assert body["summary"]["total"] == 4
+ assert {c["type"]: c["count"] for c in body["summary"]["by_type"]} == {
+ "extract_class": 1,
+ "extract_helper": 1,
+ "move_method": 1,
+ "break_cycle": 1,
+ }
+
+ plans = body["plans"]
+ assert len(plans) == 4
+ # Every plan carries its id, re-hydrated dicts, and a rank score.
+ for p in plans:
+ assert p["id"]
+ assert isinstance(p["plan"], dict)
+ assert p["rank_score"] > 0
+ # Ranked, not raw DB order: the highest rank_score is first.
+ scores = [p["rank_score"] for p in plans]
+ assert scores == sorted(scores, reverse=True)
+
+
+async def test_type_filter_narrows_plans_but_keeps_summary(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ resp = await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets",
+ params={"refactoring_type": "break_cycle"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert [p["refactoring_type"] for p in body["plans"]] == ["break_cycle"]
+ # Summary still reflects all four types so the chips can show totals.
+ assert body["summary"]["total"] == 4
+
+
+async def test_plan_detail_by_id(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]
+ target = next(p for p in listed if p["refactoring_type"] == "break_cycle")
+
+ resp = await client.get(f"/api/repos/{repo_id}/refactoring/{target['id']}")
+ assert resp.status_code == 200
+ detail = resp.json()
+ assert detail["id"] == target["id"]
+ assert detail["plan"]["cut_edges"] == [{"from": "pkg/a.py", "to": "pkg/b.py"}]
+
+
+async def test_plan_detail_unknown_id_404(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ resp = await client.get(f"/api/repos/{repo_id}/refactoring/deadbeef")
+ assert resp.status_code == 404
+
+
+async def test_centrality_breaks_ties_in_ranking(client: AsyncClient, app) -> None:
+ """Two identical plans differing only by file centrality: the one on the
+ high-in-degree (hub) file must rank first. Exercises the list endpoint's
+ materialized graph_metrics → centrality path."""
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ async with app.state.session_factory() as session:
+ await crud.batch_upsert_graph_metrics(session, repo_id, {
+ "pkg/hub.py": {"in_degree": 25, "out_degree": 1},
+ "pkg/leaf.py": {"in_degree": 0, "out_degree": 1},
+ })
+ # Same type, effort, confidence, impact, blast — only the file differs.
+ common = {
+ "refactoring_type": "extract_class",
+ "target_symbol": "C",
+ "line_start": 1,
+ "line_end": 50,
+ "plan": {"groups": [{"name": None, "methods": ["a"], "fields": ["x"]}]},
+ "evidence": {"lcom4": 2},
+ "impact_delta": 1.0,
+ "effort_bucket": "M",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "medium",
+ "source_biomarker": "low_cohesion",
+ }
+ await crud.save_refactoring_suggestions(session, repo_id, [
+ {**common, "file_path": "pkg/leaf.py"},
+ {**common, "file_path": "pkg/hub.py"},
+ ])
+ await session.commit()
+
+ body = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()
+ files = [p["file_path"] for p in body["plans"]]
+ assert files == ["pkg/hub.py", "pkg/leaf.py"]
+ assert body["plans"][0]["rank_score"] > body["plans"][1]["rank_score"]
+
+
+async def test_min_confidence_filters(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ resp = await client.get(
+ f"/api/repos/{repo_id}/refactoring/targets",
+ params={"min_confidence": "high"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ # Only the two high-confidence plans survive (extract_class, extract_helper).
+ assert body["summary"]["total"] == 2
+ assert {p["refactoring_type"] for p in body["plans"]} == {"extract_class", "extract_helper"}