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): lead with what the pile actually is, and plot the plans whose axes spread (#1151)

Raghav Chamadiyab7729d9aa794
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 8e55c4a47..db1519e53 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -67,6 +67,19 @@ class RefactoringPlanResponse(BaseModel):
# 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
+ # Two plot-ready figures, served rather than derived client-side.
+ #
+ # `dependents` is the file's in-degree — the same centrality the rank reads,
+ # so every type reports it the same way. The blast-radius dict was the only
+ # other source and it carries the count under `file_count`, `dependents_count`
+ # or `callers` depending on which detector wrote it, which is how one file
+ # ended up reporting two different dependent counts from two of its plans.
+ #
+ # Both default to 0 rather than being optional: a repo with no graph metrics
+ # or no health pass yet is a real state, and 0 reads as "not measured" in the
+ # same place a missing field would have.
+ dependents: int = 0
+ file_nloc: int = 0
class RefactoringTypeCount(BaseModel):
@@ -125,7 +138,9 @@ def _row_to_suggestion(row: Any) -> RefactoringSuggestion:
def _to_response(
- sug: RefactoringSuggestion, centrality: dict[str, float]
+ sug: RefactoringSuggestion,
+ centrality: dict[str, float],
+ nloc: dict[str, int] | None = None,
) -> RefactoringPlanResponse:
return RefactoringPlanResponse(
id=getattr(sug, "id", ""),
@@ -142,9 +157,18 @@ def _to_response(
confidence=sug.confidence,
source_biomarker=sug.source_biomarker,
rank_score=round(score(sug, centrality), 4),
+ dependents=int(centrality.get(sug.file_path, 0.0)),
+ file_nloc=int((nloc or {}).get(sug.file_path, 0)),
)
+async def _nloc_map(session: AsyncSession, repo_id: str) -> dict[str, int]:
+ """File-path → line count, from the health pass. Empty when no health
+ snapshot exists yet, which leaves every plan's ``file_nloc`` at 0."""
+ metrics = await crud.get_health_metrics(session, repo_id)
+ return {m.file_path: int(m.nloc or 0) for m in metrics}
+
+
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
@@ -167,9 +191,7 @@ async def get_refactoring_targets(
description="Filter to one type: extract_class | extract_helper | move_method | break_cycle",
),
min_confidence: str | None = Query(None, description="low | medium | high"),
- file_path: str | None = Query(
- None, description="Filter plans to one repo-relative file path"
- ),
+ file_path: str | None = Query(None, description="Filter plans to one repo-relative file path"),
session: AsyncSession = Depends(get_db_session),
) -> RefactoringTargetsResponse:
"""Ranked refactoring plans for the repo, filterable by type, confidence,
@@ -181,6 +203,7 @@ async def get_refactoring_targets(
under a confidence filter.
"""
centrality = await _centrality_map(session, repo_id)
+ nloc = await _nloc_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.
@@ -209,7 +232,7 @@ async def get_refactoring_targets(
ranked = rank_suggestions(suggestions, centrality=centrality)
return RefactoringTargetsResponse(
summary=summary,
- plans=[_to_response(s, centrality) for s in ranked],
+ plans=[_to_response(s, centrality, nloc) for s in ranked],
)
@@ -332,10 +355,22 @@ async def get_refactoring_plan(
for path in files:
degrees = await crud.get_node_degree_counts(session, repo_id, path)
centrality[path] = float(degrees.get("in_degree") or 0)
+ # The list endpoint reads in-degree from the materialized `graph_metrics`
+ # snapshot; the loop above counts live edges. The two can disagree, and a
+ # plan whose `dependents` changed between the row you clicked and the panel
+ # that opened is the bug this field exists to end. The snapshot wins for the
+ # plan's own file; edge counts still serve the blast-file caller rollup,
+ # which is a different question.
+ metrics = await crud.get_graph_metrics(session, repo_id)
+ snapshot = metrics.get(sug.file_path)
+ if snapshot is not None and snapshot.get("in_degree") is not None:
+ centrality[sug.file_path] = float(snapshot["in_degree"])
# 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)
+ metrics = await crud.get_health_metrics(session, repo_id, file_paths=[sug.file_path])
+ nloc = {m.file_path: int(m.nloc or 0) for m in metrics}
+ return _to_response(sug, centrality, nloc)
# ---------------------------------------------------------------------------
diff --git a/packages/ui/__tests__/refactoring/structural.test.ts b/packages/ui/__tests__/refactoring/structural.test.ts
new file mode 100644
index 000000000..9ca82b09c
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/structural.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ MAP_MIN_POINTS,
+ isStructural,
+ planPoint,
+ planReason,
+ STRUCTURAL_TYPES,
+ type RefactoringPlan,
+} from "../../src/refactoring/types";
+
+function plan(over: Partial<RefactoringPlan> = {}): RefactoringPlan {
+ return {
+ id: "p1",
+ refactoring_type: "split_file",
+ file_path: "pkg/models.py",
+ target_symbol: "models.py -> 6 files",
+ line_start: null,
+ line_end: null,
+ plan: {},
+ evidence: {},
+ impact_delta: 0,
+ effort_bucket: "XL",
+ blast_radius: {},
+ confidence: "high",
+ source_biomarker: "",
+ rank_score: 1,
+ ...over,
+ };
+}
+
+describe("isStructural", () => {
+ it("separates the shape-changing types from the local ones", () => {
+ for (const type of STRUCTURAL_TYPES) {
+ expect(isStructural(plan({ refactoring_type: type }))).toBe(true);
+ }
+ expect(isStructural(plan({ refactoring_type: "extract_helper" }))).toBe(false);
+ expect(isStructural(plan({ refactoring_type: "extract_method" }))).toBe(false);
+ });
+
+ it("treats an unknown type as local rather than throwing", () => {
+ expect(isStructural(plan({ refactoring_type: "invent_monad" }))).toBe(false);
+ });
+});
+
+describe("planPoint", () => {
+ it("returns coordinates when both figures are measured", () => {
+ expect(planPoint(plan({ dependents: 195, file_nloc: 1052 }))).toEqual({ x: 195, y: 1052 });
+ });
+
+ it("drops a plan whose figures are missing, rather than plotting it at the origin", () => {
+ // An older backend omits both fields entirely.
+ expect(planPoint(plan())).toBeNull();
+ // A repo with graph metrics but no health pass has one and not the other.
+ expect(planPoint(plan({ dependents: 12 }))).toBeNull();
+ expect(planPoint(plan({ file_nloc: 400 }))).toBeNull();
+ });
+
+ it("treats a genuine zero as unmeasured", () => {
+ // 0 dependents is what an unindexed file and an unimported file both report,
+ // and the map cannot tell them apart. A false cluster on the axis would be
+ // worse than an honest omission the key row counts.
+ expect(planPoint(plan({ dependents: 0, file_nloc: 900 }))).toBeNull();
+ });
+});
+
+describe("planReason", () => {
+ it("reads split-file evidence into one sentence", () => {
+ const reason = planReason(
+ plan({
+ evidence: {
+ file_nloc: 1052,
+ symbol_count: 39,
+ group_count: 6,
+ intra_edges: 45,
+ cut_edges: 6,
+ cochange_edges: 51,
+ },
+ }),
+ );
+ expect(reason).toContain("1,052 lines and 39 symbols");
+ expect(reason).toContain("6 of 45 internal edges cross a seam");
+ expect(reason).toContain("51 pairs");
+ });
+
+ it("says so when a split has a clean seam", () => {
+ const reason = planReason(
+ plan({ evidence: { file_nloc: 426, symbol_count: 22, group_count: 4, intra_edges: 15, cut_edges: 0 } }),
+ );
+ expect(reason).toContain("No edges cross a seam");
+ });
+
+ it("counts a cycle and its cuts", () => {
+ const reason = planReason(
+ plan({
+ refactoring_type: "break_cycle",
+ evidence: { cycle_size: 7, edge_count: 9, cut_count: 3 },
+ }),
+ );
+ expect(reason).toBe("7 modules import each other in a ring across 9 edges. 3 cuts open it.");
+ });
+
+ it("keeps the singular readable", () => {
+ const reason = planReason(
+ plan({
+ refactoring_type: "break_cycle",
+ evidence: { cycle_size: 2, edge_count: 2, cut_count: 1 },
+ }),
+ );
+ expect(reason).toContain("1 cut opens it");
+ });
+
+ it("returns an empty string when there is no evidence, so a caller renders nothing", () => {
+ expect(planReason(plan({ evidence: {} }))).toBe("");
+ expect(planReason(plan({ refactoring_type: "break_cycle", evidence: {} }))).toBe("");
+ expect(planReason(plan({ refactoring_type: "invent_monad" }))).toBe("");
+ });
+});
+
+describe("MAP_MIN_POINTS", () => {
+ it("is high enough that a scatter is never drawn over a handful of dots", () => {
+ // The floor exists so a repo with two structural plans gets rows instead of
+ // two marks under two axis labels. Guarded because lowering it is the kind
+ // of change that looks harmless in a diff.
+ expect(MAP_MIN_POINTS).toBeGreaterThanOrEqual(5);
+ });
+});
diff --git a/packages/ui/src/refactoring/index.ts b/packages/ui/src/refactoring/index.ts
index 0d448bada..52e5e43ef 100644
--- a/packages/ui/src/refactoring/index.ts
+++ b/packages/ui/src/refactoring/index.ts
@@ -5,8 +5,13 @@ export * from "./plan-before";
export * from "./plan-comparison";
export * from "./diff-view";
export * from "./generate-code-panel";
+export * from "./plan-rows";
+// Retired from the web surface, still mounted by the VS Code webview, which
+// has not been reworked. A use was removed here, not the component.
export * from "./refactoring-plan-card";
-export * from "./refactoring-quadrant";
-export * from "./refactoring-modal";
+export * from "./structural-map";
+export * from "./start-here";
+export * from "./refactoring-lede";
+export * from "./refactoring-drawer";
export * from "./refactoring-settings-card";
export * from "./refactoring-board";
diff --git a/packages/ui/src/refactoring/plan-before.tsx b/packages/ui/src/refactoring/plan-before.tsx
index 9f7fead26..9261e2889 100644
--- a/packages/ui/src/refactoring/plan-before.tsx
+++ b/packages/ui/src/refactoring/plan-before.tsx
@@ -1,6 +1,5 @@
"use client";
-import { typeAccent } from "./meta";
import {
cutEdges,
cycleMembers,
@@ -32,8 +31,19 @@ function baseName(path: string): string {
* so the issue reads at a glance — a tangled class, stacked duplicate sites, a
* misplaced method reaching across, or a closed import loop.
*/
+/**
+ * One accent for every type, not six.
+ *
+ * These panels used to paint from `--color-refactor-*`, a qualitative palette
+ * of six hues. On a real index two types are 96% of all plans, so the palette
+ * separated categories that barely occur — and `extract_helper`'s green is the
+ * same `#34d399` as `--color-success`, which paints the recovered-health badge
+ * a few pixels away. Two marks on one object may not share a colour.
+ */
+const ACCENT = "var(--color-accent-fill)";
+
export function PlanBefore({ plan }: PlanBeforeProps) {
- const accent = typeAccent(plan.refactoring_type);
+ const accent = ACCENT;
if (plan.refactoring_type === "extract_class") {
const groups = extractClassGroups(plan);
diff --git a/packages/ui/src/refactoring/plan-comparison.tsx b/packages/ui/src/refactoring/plan-comparison.tsx
index 1cb7412e2..0b035b594 100644
--- a/packages/ui/src/refactoring/plan-comparison.tsx
+++ b/packages/ui/src/refactoring/plan-comparison.tsx
@@ -1,7 +1,6 @@
"use client";
-import { ArrowDown, ArrowRight, Check } from "lucide-react";
-import { typeAccent } from "./meta";
+import { ArrowDown, ArrowRight } from "lucide-react";
import { PlanBefore } from "./plan-before";
import { PlanDetail } from "./plan-detail";
import type { RefactoringPlan } from "./types";
@@ -17,14 +16,18 @@ export interface PlanComparisonProps {
* "before" is the synthesized problem picture. Stacks on narrow viewports.
*/
export function PlanComparison({ plan, fileHref }: PlanComparisonProps) {
- const accent = typeAccent(plan.refactoring_type);
+ // Before and after are a sequence, and the layout already shows it: two
+ // columns with an arrow between them, in reading order. Painting the first
+ // red and the second in the type's hue spent two colours restating that, and
+ // red in particular is reserved for a health band. Both halves are labelled
+ // instead.
+ const accent = "var(--color-accent-fill)";
return (
<div className="relative grid gap-3 md:grid-cols-2">
{/* before */}
<div className="rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/40 p-4">
- <div className="mb-3 flex items-center gap-1.5">
- <span className="h-2 w-2 rounded-full bg-[var(--color-error)]" aria-hidden />
- <span className="text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <div className="mb-3">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Today
</span>
</div>
@@ -55,16 +58,9 @@ export function PlanComparison({ plan, fileHref }: PlanComparisonProps) {
</div>
{/* after */}
- <div
- className="rounded-2xl border p-4"
- style={{
- borderColor: `color-mix(in srgb, ${accent} 40%, transparent)`,
- backgroundColor: `color-mix(in srgb, ${accent} 5%, transparent)`,
- }}
- >
- <div className="mb-3 flex items-center gap-1.5">
- <Check className="h-3.5 w-3.5" style={{ color: accent }} />
- <span className="text-xs font-semibold uppercase tracking-wide" style={{ color: accent }}>
+ <div className="rounded-2xl border border-[var(--color-border-default)] p-4">
+ <div className="mb-3">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-secondary)]">
After
</span>
</div>
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index aa56dfbbc..c470ef218 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -1,7 +1,6 @@
"use client";
import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";
-import { typeAccent } from "./meta";
import {
blastFiles,
cutEdges,
@@ -104,8 +103,11 @@ function CodeBlock({ code, startLine }: { code: string; startLine: number | null
* 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.
*/
+/** One accent for every type. See the note in `plan-before.tsx`. */
+const ACCENT = "var(--color-accent-fill)";
+
export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProps) {
- const accent = typeAccent(plan.refactoring_type);
+ const accent = ACCENT;
if (plan.refactoring_type === "extract_class") {
const groups = extractClassGroups(plan).filter(
diff --git a/packages/ui/src/refactoring/plan-rows.tsx b/packages/ui/src/refactoring/plan-rows.tsx
new file mode 100644
index 000000000..0fdf4500a
--- /dev/null
+++ b/packages/ui/src/refactoring/plan-rows.tsx
@@ -0,0 +1,220 @@
+"use client";
+
+/**
+ * The full plan list, as hairline rows.
+ *
+ * This replaces a grid of `RefactoringPlanCard`s. Each card carried a
+ * type-coloured rail, a tinted type chip, a bordered metric footer and a second
+ * bordered strip holding its own AI-prompt button — four borders and two click
+ * targets per plan, sixty at a time. Cards also forced three truncations each
+ * (filename, directory, synopsis), which is a layout decision reported to the
+ * reader as missing content.
+ *
+ * Two marks that are now conditional rather than universal, per "mark only what
+ * needs attention": confidence renders only when it is not high (medium is 66%
+ * of plans and high is the rest, so a dot on every row separated nothing), and
+ * recovered health renders only when there is any (1,399 of 1,819 plans recover
+ * under half a point).
+ */
+
+import * as React from "react";
+
+import { formatNumber } from "../lib/format";
+import { typeMeta } from "./meta";
+import { blastCount, planSynopsis, type RefactoringPlan } from "./types";
+
+export interface PlanRowsProps {
+ plans: RefactoringPlan[];
+ onOpen?: ((plan: RefactoringPlan) => void) | undefined;
+ /** The overflow verb: hand this plan to a coding agent. */
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Link to the file, used by the overflow menu. */
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ /** Lit from the map above, when a row is also plotted. */
+ highlightedId?: string | null | undefined;
+}
+
+const EFFORT_WORD: Record<string, string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+ XL: "Extra large",
+};
+
+export function PlanRows({
+ plans,
+ onOpen,
+ onAiPrompt,
+ fileHref,
+ highlightedId,
+}: PlanRowsProps) {
+ return (
+ <div className="flex flex-col">
+ {plans.map((plan) => (
+ <PlanRow
+ key={plan.id}
+ plan={plan}
+ onOpen={onOpen}
+ onAiPrompt={onAiPrompt}
+ fileHref={fileHref}
+ lit={plan.id === highlightedId}
+ />
+ ))}
+ </div>
+ );
+}
+
+function PlanRow({
+ plan,
+ onOpen,
+ onAiPrompt,
+ fileHref,
+ lit,
+}: {
+ plan: RefactoringPlan;
+ onOpen?: ((plan: RefactoringPlan) => void) | undefined;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+ lit: boolean;
+}) {
+ const meta = typeMeta(plan.refactoring_type);
+ const effort = EFFORT_WORD[plan.effort_bucket || "M"] ?? plan.effort_bucket;
+ const blast = blastCount(plan);
+ const gain = plan.impact_delta;
+ const href = fileHref?.(plan.file_path, plan.line_start);
+
+ return (
+ <div
+ data-refactoring-plan={plan.id}
+ className={`grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-5 gap-y-2 border-t border-[var(--color-border-default)] px-3 py-3 lg:grid-cols-[128px_minmax(0,1fr)_170px_120px_32px] lg:items-center ${
+ lit ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]"
+ }`}
+ >
+ <div className="order-2 text-xs text-[var(--color-text-secondary)] lg:order-none">
+ {meta.label}
+ </div>
+
+ <button
+ type="button"
+ onClick={onOpen ? () => onOpen(plan) : undefined}
+ disabled={!onOpen}
+ className="group order-1 col-span-2 min-w-0 text-left lg:order-none lg:col-span-1"
+ >
+ <span className="block break-words font-mono text-[13.5px] font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
+ {plan.target_symbol || planSynopsis(plan) || meta.label}
+ </span>
+ <span className="mt-0.5 block break-all font-mono text-[11.5px] text-[var(--color-text-tertiary)]">
+ {plan.file_path}
+ </span>
+ </button>
+
+ <div className="order-3 text-[12.5px] text-[var(--color-text-secondary)] lg:order-none">
+ {effort}
+ {blast > 0 ? `, ${formatNumber(blast)} file${blast === 1 ? "" : "s"}` : ""}
+ {plan.confidence !== "high" ? (
+ <span className="ml-2 inline-flex items-center gap-1.5 text-[11.5px] text-[var(--color-caution)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-current" />
+ {plan.confidence === "low" ? "low" : "medium"} confidence
+ </span>
+ ) : null}
+ </div>
+
+ <div className="order-4 text-[12.5px] tabular-nums lg:order-none">
+ {gain > 0 ? (
+ <span className="font-medium text-[var(--color-success)]">
+ +{gain.toFixed(1)} health
+ </span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">no score change</span>
+ )}
+ </div>
+
+ <div className="order-5 justify-self-end lg:order-none">
+ <RowOverflow plan={plan} onAiPrompt={onAiPrompt} href={href} />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The row's second-order verbs.
+ *
+ * Opening the plan is the row itself. Everything else lives here so a 1,819-row
+ * list is not 1,819 clusters of controls the reader has to parse before they can
+ * read a row — and so each verb can have its real name rather than an
+ * abbreviation that only expands for someone who already knows the model.
+ */
+function RowOverflow({
+ plan,
+ onAiPrompt,
+ href,
+}: {
+ plan: RefactoringPlan;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ href?: string | undefined;
+}) {
+ const [open, setOpen] = React.useState(false);
+ const ref = React.useRef<HTMLDivElement | null>(null);
+
+ React.useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ if (!onAiPrompt && !href) return null;
+
+ return (
+ <div className="relative" ref={ref}>
+ <button
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded={open}
+ aria-label={`More actions for ${plan.file_path}`}
+ onClick={() => setOpen((v) => !v)}
+ className="rounded-md px-1.5 py-1 leading-none text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-inset)] hover:text-[var(--color-text-primary)]"
+ >
+ <span aria-hidden>&#183;&#183;&#183;</span>
+ </button>
+ {open ? (
+ <div
+ role="menu"
+ className="absolute right-0 top-full z-20 mt-1 w-56 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-md"
+ >
+ {onAiPrompt ? (
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setOpen(false);
+ onAiPrompt(plan);
+ }}
+ className="block w-full px-3 py-2 text-left text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ Copy prompt for an agent
+ </button>
+ ) : null}
+ {href ? (
+ <a
+ href={href}
+ role="menuitem"
+ className="block px-3 py-2 text-[13px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ Open file
+ </a>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index 2f1adf53c..585cd4a53 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -1,95 +1,124 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import { Search, Wrench } from "lucide-react";
+/**
+ * The Refactoring surface.
+ *
+ * Lede, then the structural plans as a field with the top few ranked under it,
+ * then every plan as hairline rows. What used to be here was a priority-by-
+ * effort quadrant over a grid of cards; both were replaced for reasons recorded
+ * in `structural-map.tsx` and `plan-rows.tsx`.
+ *
+ * The list controls survive largely intact — search, sort, effort — with one
+ * removal: the confidence filter no longer offers "low", because no detector
+ * has ever emitted a low-confidence plan and the chip filtered to zero every
+ * time it was clicked. It is built from the confidences actually present rather
+ * than from the type, so it disappears entirely on a repo whose plans are all
+ * one confidence.
+ */
+
+import * as React from "react";
+import { Search } from "lucide-react";
+
import { Input } from "../ui/input";
-import { RefactoringPlanCard } from "./refactoring-plan-card";
-import { RefactoringQuadrant } from "./refactoring-quadrant";
-import { RefactoringModal } from "./refactoring-modal";
-import { typeAccent, typeMeta, CONFIDENCE_LABEL, TYPE_ORDER } from "./meta";
+import { PlanRows } from "./plan-rows";
+import { RefactoringLede } from "./refactoring-lede";
+import { StartHere } from "./start-here";
+import { CONFIDENCE_LABEL } from "./meta";
import {
blastCount,
+ isStructural,
type Confidence,
type EffortBucket,
- type GeneratedCode,
type RefactoringPlan,
- type RefactoringSummary,
} from "./types";
const PAGE_SIZE = 60;
const EFFORTS: EffortBucket[] = ["S", "M", "L", "XL"];
const EFFORT_RANK: Record<EffortBucket, number> = { S: 0, M: 1, L: 2, XL: 3 };
-const CONFIDENCES: Confidence[] = ["high", "medium", "low"];
+const EFFORT_LABEL_LONG: Record<EffortBucket, string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+ XL: "Extra large",
+};
+const CONFIDENCE_ORDER: Confidence[] = ["high", "medium", "low"];
-type SortKey = "priority" | "health" | "effort" | "blast" | "file";
+type SortKey = "leverage" | "health" | "effort" | "blast" | "file";
const SORT_OPTIONS: { value: SortKey; label: string }[] = [
- { value: "priority", label: "Priority" },
+ // "Leverage" names what the backend rank actually blends: recovered health,
+ // how depended-upon the file is, and how much rides along. It used to be
+ // labelled "Priority", which named nothing.
+ { value: "leverage", label: "Leverage" },
{ value: "health", label: "Health recovered" },
- { value: "effort", label: "Effort (low first)" },
- { value: "blast", label: "Blast radius" },
- { value: "file", label: "File (A–Z)" },
+ { value: "effort", label: "Effort, small first" },
+ { value: "blast", label: "Files touched" },
+ { value: "file", label: "File, A to Z" },
];
export interface RefactoringBoardProps {
+ /** Plans for the active type filter. */
plans: RefactoringPlan[];
- summary?: RefactoringSummary;
- /** Open the AI-prompt modal for a plan (host owns the modal + flavor). */
+ /** Every plan, unfiltered — the lede and Start here describe the whole repo,
+ * not the tab you happen to be on. This is also where the per-type counts
+ * come from, which is why the board no longer takes a `summary`: the
+ * endpoint's summary and the plan list could disagree under a filter, and
+ * two sources for one number is how a tab badge starts lying. */
+ allPlans?: RefactoringPlan[] | undefined;
+ indexedFileCount?: number | undefined;
+ onOpen?: ((plan: RefactoringPlan) => void) | undefined;
onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- /** Opt-in LLM code generation for a plan (host owns the API call). Passed
- * through to the inspector modal; omit to hide the action. */
- onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
- /** Link to repo settings (provider/model), shown beside the Generate action. */
- settingsHref?: string | undefined;
fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
- /** Show the priority×effort quadrant centerpiece (default true). */
- showQuadrant?: boolean;
+ /** Jump the type filter to the structural set. */
+ onSeeStructural?: (() => void) | undefined;
+ /** Hide the lede and Start here — for hosts that render their own header. */
+ showLede?: boolean;
emptyTitle?: string;
emptyHint?: string;
}
-/**
- * The Refactoring surface. The priority×effort quadrant is the full-width
- * centerpiece; a searchable, sortable, filterable grid of compact plan cards
- * sits below it. Clicking the quadrant or a card opens the visual modal for
- * that one plan. No table.
- */
export function RefactoringBoard({
plans,
- summary,
+ allPlans,
+ indexedFileCount,
+ onOpen,
onAiPrompt,
- onGenerateCode,
- settingsHref,
fileHref,
- showQuadrant = true,
+ onSeeStructural,
+ showLede = 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, a cycle worth cutting, or a file worth decomposing.",
+ emptyHint = "Plans appear here when a file is worth splitting, a cycle worth cutting, a class worth extracting, or a repeated block worth sharing.",
}: RefactoringBoardProps) {
- const [highlighted, setHighlighted] = useState<string | null>(null);
- const [selected, setSelected] = useState<RefactoringPlan | null>(null);
- const [modalOpen, setModalOpen] = useState(false);
+ const [query, setQuery] = React.useState("");
+ const [sortKey, setSortKey] = React.useState<SortKey>("leverage");
+ const [effortSel, setEffortSel] = React.useState<Set<EffortBucket>>(new Set());
+ const [confSel, setConfSel] = React.useState<Set<Confidence>>(new Set());
+ const [visibleCount, setVisibleCount] = React.useState(PAGE_SIZE);
- // List controls — make hundreds of plans browsable.
- const [query, setQuery] = useState("");
- const [sortKey, setSortKey] = useState<SortKey>("priority");
- const [effortSel, setEffortSel] = useState<Set<EffortBucket>>(new Set());
- const [confSel, setConfSel] = useState<Set<Confidence>>(new Set());
+ const every = allPlans ?? plans;
+ const structural = React.useMemo(() => every.filter(isStructural), [every]);
- // 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);
+ // Only offer confidences that occur. A filter is worth building where there
+ // is something to subtract from.
+ const confidencesPresent = React.useMemo(() => {
+ const present = new Set(every.map((p) => p.confidence || "medium"));
+ return CONFIDENCE_ORDER.filter((c) => present.has(c));
+ }, [every]);
- const toggle = useCallback(<T,>(setter: React.Dispatch<React.SetStateAction<Set<T>>>, value: T) => {
- setter((cur) => {
- const next = new Set(cur);
- if (next.has(value)) next.delete(value);
- else next.add(value);
- return next;
- });
- }, []);
+ const toggle = React.useCallback(
+ <T,>(setter: React.Dispatch<React.SetStateAction<Set<T>>>, value: T) => {
+ setter((cur) => {
+ const next = new Set(cur);
+ if (next.has(value)) next.delete(value);
+ else next.add(value);
+ return next;
+ });
+ },
+ [],
+ );
- const processed = useMemo(() => {
+ const processed = React.useMemo(() => {
const q = query.trim().toLowerCase();
let out = plans.filter((p) => {
if (q && !`${p.file_path} ${p.target_symbol}`.toLowerCase().includes(q)) return false;
@@ -97,8 +126,8 @@ export function RefactoringBoard({
if (confSel.size && !confSel.has((p.confidence || "medium") as Confidence)) return false;
return true;
});
- // `priority` keeps the backend's rank order; the rest sort a copy.
- if (sortKey !== "priority") {
+ // `leverage` keeps the backend's rank order; the rest sort a copy.
+ if (sortKey !== "leverage") {
out = [...out].sort((a, b) => {
switch (sortKey) {
case "health":
@@ -120,91 +149,58 @@ export function RefactoringBoard({
return out;
}, [plans, query, sortKey, effortSel, confSel]);
- // Reset the window whenever the visible set changes (filter/sort/search/type).
- useEffect(() => {
+ React.useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [processed]);
- const openPlan = useCallback((plan: RefactoringPlan) => {
- setSelected(plan);
- setModalOpen(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) {
+ if (every.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>
+ <div className="border-t border-[var(--color-border-default)] pt-10 text-center">
<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>
+ <p className="mx-auto mt-1.5 max-w-[56ch] text-sm text-[var(--color-text-tertiary)]">
+ {emptyHint}
+ </p>
</div>
);
}
- const counts = new Map((summary?.by_type ?? []).map((c) => [c.type, c.count]));
const filtersActive = query.trim() !== "" || effortSel.size > 0 || confSel.size > 0;
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>
+ <div className="space-y-10">
+ {showLede ? (
+ <RefactoringLede plans={every} indexedFileCount={indexedFileCount} />
+ ) : null}
+
+ {showLede && structural.length > 0 ? (
+ <StartHere plans={structural} onOpen={onOpen} onSeeAll={onSeeStructural} />
) : null}
- <section className="space-y-4">
- {/* control bar */}
+ <section className="space-y-4 border-t border-[var(--color-border-default)] pt-8">
+ <div>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">All plans</h2>
+ <p className="mt-1 max-w-[68ch] text-sm text-[var(--color-text-secondary)]">
+ Ordered by leverage. Every plan opens the same inspector: what changes, why it was
+ flagged, and what else it touches.
+ </p>
+ </div>
+
<div className="flex flex-wrap items-center gap-3">
<div className="relative min-w-[220px] flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-text-tertiary)]" />
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search file or symbol…"
+ placeholder="Search file or symbol"
className="pl-9"
aria-label="Search plans"
/>
</div>
-
- <div className="flex items-center gap-1.5">
- <label htmlFor="refactoring-sort" className="text-xs text-[var(--color-text-tertiary)]">
+ <div className="flex items-center gap-2">
+ <label
+ htmlFor="refactoring-sort"
+ className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"
+ >
Sort
</label>
<select
@@ -222,10 +218,9 @@ export function RefactoringBoard({
</div>
</div>
- {/* quick filters */}
- <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
- <div className="flex items-center gap-1.5">
- <span className="text-[11px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
Effort
</span>
{EFFORTS.map((e) => (
@@ -233,31 +228,35 @@ export function RefactoringBoard({
key={e}
active={effortSel.has(e)}
onClick={() => toggle(setEffortSel, e)}
- label={e}
- />
- ))}
- </div>
- <div className="flex items-center gap-1.5">
- <span className="text-[11px] uppercase tracking-wide text-[var(--color-text-tertiary)]">
- Confidence
- </span>
- {CONFIDENCES.map((c) => (
- <FilterChip
- key={c}
- active={confSel.has(c)}
- onClick={() => toggle(setConfSel, c)}
- label={CONFIDENCE_LABEL[c]}
+ label={EFFORT_LABEL_LONG[e]}
/>
))}
</div>
+ {confidencesPresent.length > 1 ? (
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Confidence
+ </span>
+ {confidencesPresent.map((c) => (
+ <FilterChip
+ key={c}
+ active={confSel.has(c)}
+ onClick={() => toggle(setConfSel, c)}
+ label={CONFIDENCE_LABEL[c]}
+ />
+ ))}
+ </div>
+ ) : null}
</div>
- {/* count + reset */}
<div className="flex items-center justify-between">
- <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
- {processed.length} plan{processed.length === 1 ? "" : "s"}
+ <h3 className="text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {processed.length.toLocaleString()} plan{processed.length === 1 ? "" : "s"}
{filtersActive ? (
- <span className="font-normal text-[var(--color-text-tertiary)]"> of {plans.length}</span>
+ <span className="font-normal text-[var(--color-text-tertiary)]">
+ {" "}
+ of {plans.length.toLocaleString()}
+ </span>
) : null}
</h3>
{filtersActive ? (
@@ -276,32 +275,27 @@ export function RefactoringBoard({
</div>
{processed.length === 0 ? (
- <div className="rounded-2xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-6 py-12 text-center text-sm text-[var(--color-text-tertiary)]">
+ <p className="border-t border-[var(--color-border-default)] py-10 text-center text-sm text-[var(--color-text-tertiary)]">
No plans match these filters.
- </div>
+ </p>
) : (
<>
- <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
- {processed.slice(0, visibleCount).map((plan) => (
- <RefactoringPlanCard
- key={plan.id}
- plan={plan}
- onOpen={openPlan}
- onAiPrompt={onAiPrompt}
- highlighted={highlighted === plan.id}
- />
- ))}
- </div>
+ <PlanRows
+ plans={processed.slice(0, visibleCount)}
+ onOpen={onOpen}
+ onAiPrompt={onAiPrompt}
+ fileHref={fileHref}
+ />
{processed.length > visibleCount ? (
- <div className="flex justify-center pt-1">
+ <div className="flex justify-center border-t border-[var(--color-border-default)] pt-5">
<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-hover)] hover:text-[var(--color-text-primary)]"
>
Show {Math.min(PAGE_SIZE, processed.length - visibleCount)} more
- <span className="text-[var(--color-text-tertiary)]">
- · {processed.length - visibleCount} left
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ · {(processed.length - visibleCount).toLocaleString()} left
</span>
</button>
</div>
@@ -309,16 +303,6 @@ export function RefactoringBoard({
</>
)}
</section>
-
- <RefactoringModal
- plan={selected}
- open={modalOpen}
- onOpenChange={setModalOpen}
- onAiPrompt={onAiPrompt}
- onGenerateCode={onGenerateCode}
- settingsHref={settingsHref}
- fileHref={fileHref}
- />
</div>
);
}
diff --git a/packages/ui/src/refactoring/refactoring-drawer.tsx b/packages/ui/src/refactoring/refactoring-drawer.tsx
new file mode 100644
index 000000000..4bfbd20ce
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-drawer.tsx
@@ -0,0 +1,271 @@
+"use client";
+
+/**
+ * The plan inspector, as a right-hand drawer.
+ *
+ * It was a centred `max-w-4xl` dialog with six sections, a generated diff and a
+ * sticky footer — a reading surface wearing a modal. A drawer keeps the list on
+ * screen behind it, and lets the host put the open plan in the URL so a plan
+ * can be linked rather than only navigated to.
+ *
+ * The before-and-after itself is unchanged: `PlanComparison`, the evidence row
+ * and the blast list are the strongest work on this surface and the rework does
+ * not touch what they show. What changed is the frame. The header used to paint
+ * a gradient wash, an icon tile and the "After" panel's border from a per-type
+ * accent, which meant six hues separating categories where two types are 96% of
+ * the data — and Extract Helper's green was the same green as the health badge
+ * next to it. The type is a word now. Effort, confidence, blast radius and
+ * recovered health were three chip shapes across two sections; they are one
+ * line of prose under the title.
+ */
+
+import { Layers, Sparkles, TrendingUp, Wand2 } from "lucide-react";
+
+import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";
+import { formatNumber } from "../lib/format";
+import { PlanComparison } from "./plan-comparison";
+import { GenerateCodePanel } from "./generate-code-panel";
+import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
+import {
+ blastCount,
+ blastFiles,
+ evidenceRows,
+ planWins,
+ type Confidence,
+ type EffortBucket,
+ type GeneratedCode,
+ type RefactoringPlan,
+} from "./types";
+
+export interface RefactoringDrawerProps {
+ plan: RefactoringPlan | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Opt-in LLM code generation. Omit to hide the section entirely. */
+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
+ settingsHref?: string | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}
+
+export function RefactoringDrawer({
+ plan,
+ open,
+ onOpenChange,
+ onAiPrompt,
+ onGenerateCode,
+ settingsHref,
+ fileHref,
+}: RefactoringDrawerProps) {
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ closeLabel="Close plan"
+ // Wider than the nav sheet this primitive was written for: the
+ // before-and-after is two columns at rest, and the reading floor for the
+ // code block is what sets the minimum.
+ className="w-full max-w-[680px] sm:w-[92vw]"
+ >
+ {plan ? (
+ <DrawerBody
+ plan={plan}
+ onAiPrompt={onAiPrompt}
+ onGenerateCode={onGenerateCode}
+ settingsHref={settingsHref}
+ fileHref={fileHref}
+ />
+ ) : (
+ <SheetTitle className="sr-only">Refactoring plan</SheetTitle>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function DrawerBody({
+ plan,
+ onAiPrompt,
+ onGenerateCode,
+ settingsHref,
+ fileHref,
+}: {
+ plan: RefactoringPlan;
+ onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
+ settingsHref?: string | undefined;
+ fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
+}) {
+ const meta = typeMeta(plan.refactoring_type);
+ const effort = (plan.effort_bucket || "M") as EffortBucket;
+ const confidence = (plan.confidence || "medium") as Confidence;
+ const evidence = evidenceRows(plan);
+ const wins = planWins(plan);
+ const blast = blastFiles(plan).filter((f) => f !== plan.file_path);
+ const blastN = blastCount(plan);
+ const name = plan.file_path.split("/").pop() ?? plan.file_path;
+
+ // One line of words, in the order a reader asks: how big, how sure, how far,
+ // what it buys. Rule 4 — every figure gets a unit or a sentence.
+ const facts: string[] = [
+ `${EFFORT_LABEL[effort]} effort`,
+ `${CONFIDENCE_LABEL[confidence]} confidence`,
+ ];
+ if (blastN > 0) facts.push(`${formatNumber(blastN)} file${blastN === 1 ? "" : "s"} affected`);
+
+ return (
+ <>
+ <div className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12">
+ <div className="text-[11px] text-[var(--color-text-secondary)]">{meta.label}</div>
+ <SheetTitle className="mt-0.5 break-words font-mono text-[15px] font-semibold text-[var(--color-text-primary)]">
+ {plan.target_symbol || name}
+ </SheetTitle>
+ <p className="mt-1 break-all font-mono text-[11.5px] text-[var(--color-text-tertiary)]">
+ {plan.file_path}
+ {plan.line_start ? `:${plan.line_start}` : ""}
+ {plan.line_start && plan.line_end ? `–${plan.line_end}` : ""}
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-[var(--color-border-default)] px-5 py-2.5 text-[12.5px] text-[var(--color-text-secondary)]">
+ {facts.map((f) => (
+ <span key={f}>{f}</span>
+ ))}
+ {plan.impact_delta > 0 ? (
+ <span className="font-medium tabular-nums text-[var(--color-success)]">
+ +{plan.impact_delta.toFixed(1)} health
+ </span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">No score change</span>
+ )}
+ </div>
+
+ <div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">
+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">{meta.blurb}</p>
+
+ <section>
+ <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ The change
+ </h4>
+ <PlanComparison plan={plan} fileHref={fileHref} />
+ </section>
+
+ {onGenerateCode ? (
+ <section>
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <h4 className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <Wand2 className="h-3.5 w-3.5" />
+ Generate the code
+ </h4>
+ {settingsHref ? (
+ <a
+ href={settingsHref}
+ className="text-[11px] text-[var(--color-text-tertiary)] underline-offset-2 transition-colors hover:text-[var(--color-text-secondary)] hover:underline"
+ >
+ Change model
+ </a>
+ ) : null}
+ </div>
+ <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />
+ </section>
+ ) : null}
+
+ {wins.length > 0 ? (
+ <section>
+ <h4 className="mb-2.5 flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ <TrendingUp className="h-3.5 w-3.5" />
+ What you gain
+ </h4>
+ <ul className="space-y-1">
+ {wins.map((w) => (
+ <li
+ key={w.label}
+ className={`flex items-start gap-2 text-sm ${
+ w.hero
+ ? "font-medium text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)]"
+ }`}
+ >
+ <span
+ className="mt-[7px] h-1 w-1 shrink-0 rounded-full bg-[var(--color-text-tertiary)]"
+ aria-hidden
+ />
+ {w.label}
+ </li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
+
+ {evidence.length > 0 ? (
+ <section>
+ <h4 className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Why this was flagged
+ </h4>
+ <dl className="grid grid-cols-2 sm:grid-cols-4">
+ {evidence.map((row) => (
+ <div
+ key={row.label}
+ className="border-t border-[var(--color-border-default)] py-2 pr-3"
+ >
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] 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.length > 0 ? (
+ <section>
+ <h4 className="mb-2 flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.12em] 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="break-all font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {f}
+ </a>
+ ) : (
+ <span className="break-all font-mono text-xs text-[var(--color-text-secondary)]">
+ {f}
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ ) : null}
+ </div>
+
+ {onAiPrompt ? (
+ <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">
+ <button
+ type="button"
+ onClick={() => onAiPrompt(plan)}
+ className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-accent-fill)] px-3.5 py-2 text-sm font-semibold text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90"
+ >
+ <Sparkles className="h-4 w-4" />
+ Copy prompt for an agent
+ </button>
+ <span className="hidden text-xs text-[var(--color-text-tertiary)] sm:block">
+ The steps, the blast radius, and a completion contract.
+ </span>
+ </div>
+ ) : null}
+ </>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-lede.tsx b/packages/ui/src/refactoring/refactoring-lede.tsx
new file mode 100644
index 000000000..74d89e588
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-lede.tsx
@@ -0,0 +1,141 @@
+/**
+ * The Refactoring page's opening read.
+ *
+ * The surface used to open on a priority-by-effort scatter with no sentence
+ * anywhere above it, which made it the only ported page with no lede. The
+ * figure alone is also actively misleading here: "1,819 plans" reads as a
+ * backlog you are failing at, when 96% of it is small local tidy-ups you do
+ * while already in the file.
+ *
+ * So the prose carries the split, and the split is what the rest of the page is
+ * organised around. It is measured, not asserted — every number below is
+ * counted off the plans passed in.
+ */
+
+import type { ReactNode } from "react";
+
+import { PageLede } from "../shared/page-lede";
+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
+import { formatNumber } from "../lib/format";
+import { typeMeta } from "./meta";
+import { isStructural, planPoint, type RefactoringPlan } from "./types";
+
+export interface RefactoringLedeProps {
+ plans: RefactoringPlan[];
+ /** Files in the repo, for the "802 of 4,952 indexed" denominator. Omit and
+ * the ribbon drops the comparison rather than inventing one. */
+ indexedFileCount?: number | undefined;
+ /** Rendered under the prose. */
+ action?: ReactNode;
+}
+
+/** "46 files to split, 13 cycles to cut and 6 classes doing two jobs" — built
+ * rather than interpolated so a repo with one kind does not read "and". */
+function joinPhrases(parts: string[]): string {
+ if (parts.length <= 1) return parts[0] ?? "";
+ return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
+}
+
+/** What each structural type is, in the words someone would use out loud. */
+const STRUCTURAL_PHRASE: Record<string, (n: number) => string> = {
+ split_file: (n) => `${n} file${n === 1 ? "" : "s"} large enough to split along a real seam`,
+ break_cycle: (n) => `${n} import cycle${n === 1 ? "" : "s"} with a cuttable edge`,
+ extract_class: (n) => `${n} class${n === 1 ? "" : "es"} doing more than one job`,
+ move_method: (n) => `${n} method${n === 1 ? "" : "s"} living on the wrong class`,
+};
+
+export function RefactoringLede({ plans, indexedFileCount, action }: RefactoringLedeProps) {
+ const total = plans.length;
+ const structural = plans.filter(isStructural);
+ const local = total - structural.length;
+
+ const files = new Set(plans.map((p) => p.file_path)).size;
+ const small = plans.filter((p) => (p.effort_bucket || "M") === "S").length;
+ const recovers = plans.filter((p) => p.impact_delta >= 0.1).length;
+ const plottable = structural.filter((p) => planPoint(p) !== null).length;
+
+ const byType = new Map<string, number>();
+ for (const p of structural) byType.set(p.refactoring_type, (byType.get(p.refactoring_type) ?? 0) + 1);
+ const structuralPhrase = joinPhrases(
+ [...byType.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([type, n]) => STRUCTURAL_PHRASE[type]?.(n) ?? `${n} ${typeMeta(type).label.toLowerCase()}`),
+ );
+
+ // The largest single recovery on the page. Quoted rather than assumed,
+ // because the ceiling is what makes "rank by health recovered" a bad idea and
+ // a reader is entitled to check the claim.
+ const bestGain = plans.reduce((m, p) => Math.max(m, p.impact_delta), 0);
+ const negligible = plans.filter((p) => p.impact_delta < 0.5).length;
+
+ const stats: RibbonStat[] = [
+ {
+ label: "Files with a plan",
+ value: formatNumber(files),
+ sub: indexedFileCount ? `of ${formatNumber(indexedFileCount)} indexed` : undefined,
+ },
+ {
+ label: "Rated small effort",
+ value: total ? `${Math.round((small / total) * 100)}%` : "0%",
+ sub: `${formatNumber(small)} plan${small === 1 ? "" : "s"}`,
+ },
+ {
+ label: "Recover health",
+ value: formatNumber(recovers),
+ sub: "+0.1 or better",
+ },
+ {
+ label: "Change a file's shape",
+ value: formatNumber(structural.length),
+ sub: plottable < structural.length ? `${formatNumber(plottable)} measured` : "the rest are local",
+ },
+ ];
+
+ return (
+ <div className="space-y-6">
+ <PageLede
+ label="Open plans"
+ value={formatNumber(total)}
+ unit={files ? `across ${formatNumber(files)} file${files === 1 ? "" : "s"}` : undefined}
+ layout="beside"
+ action={action}
+ figureFooter={
+ structural.length > 0 ? (
+ <p className="text-caption text-[var(--color-text-tertiary)]">
+ {formatNumber(structural.length)} of them change a file&apos;s shape. The rest are
+ local.
+ </p>
+ ) : undefined
+ }
+ >
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ Most of this list is small.
+ </span>{" "}
+ {formatNumber(local)} plan{local === 1 ? "" : "s"} lift a slice of a long function or
+ dedupe a repeated block, and {total ? Math.round((small / total) * 100) : 0}% are rated
+ small effort. They are worth doing when you are already in the file, and they are not
+ worth a planning meeting.
+ </p>
+ {structural.length > 0 ? (
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {formatNumber(structural.length)}{" "}
+ {structural.length === 1 ? "is structural" : "are structural"}.
+ </span>{" "}
+ {structuralPhrase}. These change how the codebase is shaped, so they lead the page.
+ </p>
+ ) : null}
+ {bestGain > 0 ? (
+ <p>
+ Health recovered tops out at +{bestGain.toFixed(1)} per plan and{" "}
+ {formatNumber(negligible)} recover under half a point, so it ranks poorly on its own.
+ The order below weighs how depended-upon the file is and how much rides along with it.
+ </p>
+ ) : null}
+ </PageLede>
+
+ <StatRibbon stats={stats} />
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/refactoring-modal.tsx b/packages/ui/src/refactoring/refactoring-modal.tsx
deleted file mode 100644
index 188ad9e60..000000000
--- a/packages/ui/src/refactoring/refactoring-modal.tsx
+++ /dev/null
@@ -1,292 +0,0 @@
-"use client";
-
-import { Layers, Sparkles, TrendingUp, Wand2 } from "lucide-react";
-import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
-import { PlanComparison } from "./plan-comparison";
-import { GenerateCodePanel } from "./generate-code-panel";
-import { CONFIDENCE_LABEL, EFFORT_LABEL, typeAccent, typeMeta } from "./meta";
-import {
- blastCount,
- blastFiles,
- evidenceRows,
- planWins,
- type Confidence,
- type EffortBucket,
- type GeneratedCode,
- type RefactoringPlan,
-} from "./types";
-
-export interface RefactoringModalProps {
- plan: RefactoringPlan | null;
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- /** Opt-in LLM code generation. When provided, a "Generate code" section
- * renders a diff for the plan; omit it (e.g. on hosted / when disabled) to
- * hide the action entirely. Host owns the API call. */
- onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
- /** Link to the repo settings (provider/model). Renders a quiet link beside
- * the Generate code action when set. */
- settingsHref?: string | undefined;
- fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;
-}
-
-function fileParts(path: string): { name: string; dir: string } {
- const parts = path.split("/");
- const name = parts[parts.length - 1] ?? path;
- const dir = parts.slice(0, -1).join("/");
- return { name, dir };
-}
-
-/**
- * The plan inspector as a large, centered modal. Leads with the file, frames
- * the health it recovers as the win, and shows the refactoring as a visual
- * before→after. Mounted only for the selected plan, so the heavy visual cost
- * is paid once, on demand.
- */
-export function RefactoringModal({
- plan,
- open,
- onOpenChange,
- onAiPrompt,
- onGenerateCode,
- settingsHref,
- fileHref,
-}: RefactoringModalProps) {
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-h-[90vh] w-[calc(100%-1.5rem)] max-w-4xl gap-0 overflow-y-auto p-0">
- {plan ? (
- <ModalBody
- plan={plan}
- onAiPrompt={onAiPrompt}
- onGenerateCode={onGenerateCode}
- settingsHref={settingsHref}
- fileHref={fileHref}
- />
- ) : (
- <DialogTitle className="sr-only">Refactoring plan</DialogTitle>
- )}
- </DialogContent>
- </Dialog>
- );
-}
-
-function ModalBody({
- plan,
- onAiPrompt,
- onGenerateCode,
- settingsHref,
- fileHref,
-}: {
- plan: RefactoringPlan;
- onAiPrompt?: ((plan: RefactoringPlan) => void) | undefined;
- onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
- settingsHref?: string | 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 wins = planWins(plan);
- const blast = blastFiles(plan).filter((f) => f !== plan.file_path);
- const blastN = blastCount(plan);
- const { name, dir } = fileParts(plan.file_path);
-
- return (
- <>
- {/* header — file first, type as a colored accent, win badge on the right */}
- <div
- className="border-b border-[var(--color-border-default)] px-6 py-5 pr-12"
- style={{ background: `linear-gradient(to bottom, color-mix(in srgb, ${accent} 6%, transparent), transparent)` }}
- >
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="flex min-w-0 items-start gap-3">
- <span
- className="mt-0.5 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>
- <div className="min-w-0">
- <DialogTitle className="truncate text-base font-semibold text-[var(--color-text-primary)]">
- {name}
- </DialogTitle>
- {dir ? (
- <p className="truncate font-mono text-[11px] text-[var(--color-text-tertiary)]">{dir}</p>
- ) : null}
- <div className="mt-1.5 flex flex-wrap items-center gap-2">
- <span
- className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[11px] font-semibold"
- style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}
- >
- {meta.label}
- </span>
- {plan.target_symbol ? (
- <code className="truncate text-[11px] text-[var(--color-text-secondary)]">
- {plan.target_symbol}
- </code>
- ) : null}
- </div>
- </div>
- </div>
- {plan.impact_delta > 0 ? (
- <span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-[var(--color-success)]/10 px-3 py-1.5 text-sm font-semibold tabular-nums text-[var(--color-success)]">
- <TrendingUp className="h-4 w-4" />
- +{plan.impact_delta.toFixed(1)} health
- </span>
- ) : null}
- </div>
- </div>
-
- <div className="space-y-6 px-6 py-5">
- <p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">{meta.blurb}</p>
-
- {/* the visual before → after */}
- <section>
- <h4 className="mb-3 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
- The change
- </h4>
- <PlanComparison plan={plan} fileHref={fileHref} />
- </section>
-
- {/* generate code — opt-in LLM enrichment (plan -> diff) */}
- {onGenerateCode ? (
- <section>
- <div className="mb-3 flex items-center justify-between gap-3">
- <h4 className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">
- <Wand2 className="h-3.5 w-3.5" />
- Generate the code
- </h4>
- {settingsHref ? (
- <a
- href={settingsHref}
- className="text-[11px] text-[var(--color-text-tertiary)] underline-offset-2 transition-colors hover:text-[var(--color-text-secondary)] hover:underline"
- >
- Change model
- </a>
- ) : null}
- </div>
- <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />
- </section>
- ) : null}
-
- {/* what you gain */}
- {wins.length > 0 ? (
- <section className="rounded-2xl border border-[var(--color-success)]/25 bg-[var(--color-success)]/[0.05] p-4">
- <h4 className="mb-2.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-success)]">
- <TrendingUp className="h-3.5 w-3.5" />
- What you gain
- </h4>
- <ul className="grid gap-x-6 gap-y-1.5 sm:grid-cols-2">
- {wins.map((w) => (
- <li
- key={w.label}
- className={`flex items-center gap-2 text-sm ${
- w.hero
- ? "font-semibold text-[var(--color-text-primary)]"
- : "text-[var(--color-text-secondary)]"
- }`}
- >
- <span
- className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-success)]"
- aria-hidden
- />
- {w.label}
- </li>
- ))}
- </ul>
- <div className="mt-3 flex flex-wrap gap-2 border-t border-[var(--color-success)]/15 pt-3">
- <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}
- </div>
- </section>
- ) : null}
-
- {/* 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-4">
- {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 flex flex-col gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-6 py-4 sm:flex-row sm:items-center sm:justify-between">
- <span className="hidden text-xs text-[var(--color-text-tertiary)] sm:block">
- Hand the exact steps, blast radius, and a completion contract to your coding agent.
- </span>
- <button
- type="button"
- onClick={() => onAiPrompt(plan)}
- className="inline-flex w-full shrink-0 items-center justify-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 sm:w-auto"
- >
- <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-quadrant.tsx b/packages/ui/src/refactoring/refactoring-quadrant.tsx
deleted file mode 100644
index 65bcb3dec..000000000
--- a/packages/ui/src/refactoring/refactoring-quadrant.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-"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]);
- // The dot budget is limited, and one high-volume type (Extract Helper / clone
- // dedup often numbers in the hundreds) must not consume it all and hide the
- // rest. Seat every other type first, in rank order, then let Extract Helper
- // fill whatever capacity remains — so Split File / Move Method / Break Cycle /
- // Extract Class always get plotted.
- const data = useMemo(() => {
- const primary = scored.filter((p) => p.refactoring_type !== "extract_helper");
- const helpers = scored.filter((p) => p.refactoring_type === "extract_helper");
- return [...primary, ...helpers].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)]">
- Plotting {data.length} of {scored.length} plans — Extract Helper yields space so every
- type stays visible
- </p>
- ) : null}
- <div className="relative">
- <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Priority versus effort scatter plot" className="h-auto w-full 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/start-here.tsx b/packages/ui/src/refactoring/start-here.tsx
new file mode 100644
index 000000000..4fbc4a0e2
--- /dev/null
+++ b/packages/ui/src/refactoring/start-here.tsx
@@ -0,0 +1,144 @@
+"use client";
+
+/**
+ * The top of the Refactoring page: the structural plans as a field, and the
+ * handful worth doing first as ranked rows underneath.
+ *
+ * These are one section rather than two because they answer different halves of
+ * the same question and neither is sufficient alone. The map says which plans
+ * are expensive and far-reaching, which is a shape a sorted column cannot carry
+ * — a 1,417-line file with 11 dependents and a 1,052-line file with 195 are
+ * neighbours in a list and opposite corners here. The rows say what to do
+ * first, and carry the evidence sentence a dot has no room for.
+ *
+ * They share hover state in both directions, so the two halves read as one
+ * object: pointing at a mark lights its row, and pointing at a row lights its
+ * mark.
+ *
+ * Below `MAP_MIN_POINTS` plottable plans the map does not render. A scatter
+ * with four dots asks a reader to decode two axes to learn less than four rows
+ * already told them, and a repo with no large files would otherwise get an
+ * empty centrepiece with a confident heading over it.
+ */
+
+import * as React from "react";
+
+import { formatNumber } from "../lib/format";
+import { StructuralMap } from "./structural-map";
+import { typeMeta } from "./meta";
+import {
+ MAP_MIN_POINTS,
+ planPoint,
+ planReason,
+ planSynopsis,
+ type RefactoringPlan,
+} from "./types";
+
+export interface StartHereProps {
+ /** Structural plans, already in rank order. */
+ plans: RefactoringPlan[];
+ onOpen?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Jump to the full list filtered to structural types. */
+ onSeeAll?: (() => void) | undefined;
+ /** How many ranked rows to show under the map. */
+ leadCount?: number;
+}
+
+const EFFORT_WORD: Record<string, string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+ XL: "Extra large",
+};
+
+export function StartHere({ plans, onOpen, onSeeAll, leadCount = 5 }: StartHereProps) {
+ const [highlighted, setHighlighted] = React.useState<string | null>(null);
+
+ const plottable = React.useMemo(() => plans.filter((p) => planPoint(p) !== null), [plans]);
+ const showMap = plottable.length >= MAP_MIN_POINTS;
+ const lead = plans.slice(0, leadCount);
+
+ if (plans.length === 0) return null;
+
+ return (
+ <section className="space-y-5 border-t border-[var(--color-border-default)] pt-8">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">Start here</h2>
+ <p className="mt-1 max-w-[68ch] text-sm text-[var(--color-text-secondary)]">
+ {showMap
+ ? "Up the page is a bigger file to work through; right is more code that imports it. Top right is where a morning changes the most, and where the back-compat shim matters."
+ : "The plans that change how the codebase is laid out, ranked by how depended-upon the file is and how much rides along with it."}
+ </p>
+ </div>
+ {onSeeAll ? (
+ <button
+ type="button"
+ onClick={onSeeAll}
+ className="shrink-0 text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline"
+ >
+ See all {formatNumber(plans.length)} structural
+ </button>
+ ) : null}
+ </div>
+
+ {showMap ? (
+ <StructuralMap
+ plans={plans}
+ onSelect={onOpen}
+ highlightedId={highlighted}
+ onHighlight={setHighlighted}
+ />
+ ) : null}
+
+ <div>
+ {lead.map((plan, i) => {
+ const meta = typeMeta(plan.refactoring_type);
+ const reason = planReason(plan);
+ const effort = EFFORT_WORD[plan.effort_bucket || "M"] ?? plan.effort_bucket;
+ const lit = plan.id === highlighted;
+ return (
+ <button
+ key={plan.id}
+ type="button"
+ onClick={onOpen ? () => onOpen(plan) : undefined}
+ disabled={!onOpen}
+ onMouseEnter={() => setHighlighted(plan.id)}
+ onMouseLeave={() => setHighlighted(null)}
+ onFocus={() => setHighlighted(plan.id)}
+ onBlur={() => setHighlighted(null)}
+ className={`group grid w-full grid-cols-[28px_minmax(0,1fr)] items-start gap-4 border-t border-[var(--color-border-default)] px-3 py-4 text-left transition-colors first:border-t-0 md:grid-cols-[28px_minmax(0,1fr)_150px] md:items-center ${
+ lit ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]"
+ }`}
+ >
+ <span className="pt-0.5 font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {String(i + 1).padStart(2, "0")}
+ </span>
+ <span className="min-w-0">
+ <span className="block text-[15px] font-semibold text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
+ {planSynopsis(plan) || meta.label}
+ </span>
+ {/* Full path, no ellipsis: a truncated title reports a layout
+ decision to the reader as missing content. */}
+ <span className="mt-0.5 block break-all font-mono text-[11px] text-[var(--color-text-tertiary)]">
+ {plan.file_path}
+ </span>
+ {reason ? (
+ <span className="mt-1.5 block max-w-[70ch] text-[13px] text-[var(--color-text-secondary)]">
+ {reason}
+ </span>
+ ) : null}
+ </span>
+ <span className="mt-2 block text-xs text-[var(--color-text-tertiary)] md:mt-0 md:text-right">
+ {effort} effort
+ <br />
+ {plan.confidence === "high" ? "High" : plan.confidence === "low" ? "Low" : "Medium"}{" "}
+ confidence
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
diff --git a/packages/ui/src/refactoring/structural-map.tsx b/packages/ui/src/refactoring/structural-map.tsx
new file mode 100644
index 000000000..837b383ba
--- /dev/null
+++ b/packages/ui/src/refactoring/structural-map.tsx
@@ -0,0 +1,379 @@
+"use client";
+
+/**
+ * The structural plans as a field: file size against how much imports the file.
+ *
+ * This replaces a priority-by-effort quadrant that failed its own test. On a
+ * real index 89% of plans are rated small effort, so the effort axis put almost
+ * everything in one column and three of the four quadrant labels annotated
+ * empty space; it also plotted 120 dots of 1,819 and said so only in a caption
+ * inside the canvas. Restricting the field to the structural plans is what
+ * makes a scatter honest here — those spread across both axes (dependents 1 to
+ * 195, sizes 19 to 1,417 lines on this repo), and there are few enough to draw
+ * every one.
+ *
+ * Three things it does that the quadrant did not, all from the design language:
+ *
+ * - **Type is a shape, not a hue.** Six `--color-refactor-*` accents separated
+ * categories where two types are 96% of the data, and one of them was the
+ * same green as the health badge beside it.
+ * - **The viewBox tracks the container.** A fixed `0 0 1100 400` at
+ * `width:100%` scales its own text: 12px labels render at 4px on a phone and
+ * at 14px on a wide desktop. One unit is one CSS pixel at every width here.
+ * - **Chrome goes around it.** The key, the counts and the bound live in a
+ * hairline row underneath; only the hover card tracks the pointer, and no
+ * `<title>` child fights it for the tooltip.
+ */
+
+import * as React from "react";
+
+import { formatNumber } from "../lib/format";
+import { typeMeta } from "./meta";
+import { planPoint, type RefactoringPlan } from "./types";
+
+export interface StructuralMapProps {
+ /** Structural plans. Those without both figures are dropped and counted. */
+ plans: RefactoringPlan[];
+ onSelect?: ((plan: RefactoringPlan) => void) | undefined;
+ /** Lit from the row list, so hovering either half highlights the other. */
+ highlightedId?: string | null | undefined;
+ onHighlight?: ((id: string | null) => void) | undefined;
+}
+
+const PAD_L = 52;
+const PAD_R = 24;
+const PAD_T = 18;
+const PAD_B = 46;
+
+/** Marks are ~11px across, so the pointer needs a target bigger than the ink. */
+const HIT_RADIUS = 12;
+
+/** A deterministic sub-pixel offset, so two plans on one file do not stack into
+ * a single mark. Two detectors firing on the same file is common: a file big
+ * enough to split is often also in a cycle. */
+function jitter(seed: string): number {
+ let h = 0;
+ for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
+ return ((h % 9) - 4) * 1.1;
+}
+
+function markPath(type: string, cx: number, cy: number, r: number): string | null {
+ if (type === "break_cycle") {
+ return `M${cx} ${cy - r * 1.15}L${cx + r * 1.15} ${cy}L${cx} ${cy + r * 1.15}L${cx - r * 1.15} ${cy}Z`;
+ }
+ if (type === "extract_class" || type === "move_method") {
+ return `M${cx} ${cy - r * 1.25}L${cx + r * 1.2} ${cy + r * 0.95}L${cx - r * 1.2} ${cy + r * 0.95}Z`;
+ }
+ return null; // split_file draws as a circle
+}
+
+/** Nice round ceilings so the top gridline is a number a person would say. */
+function axisCeiling(max: number): number {
+ const step = max > 800 ? 400 : max > 200 ? 100 : max > 40 ? 20 : 5;
+ return Math.max(step, Math.ceil(max / step) * step);
+}
+
+function median(values: number[]): number {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)] ?? 0;
+}
+
+export function StructuralMap({
+ plans,
+ onSelect,
+ highlightedId,
+ onHighlight,
+}: StructuralMapProps) {
+ const wrapRef = React.useRef<HTMLDivElement | null>(null);
+ const [width, setWidth] = React.useState(0);
+
+ React.useEffect(() => {
+ const node = wrapRef.current;
+ if (!node) return;
+ const measure = () => setWidth(node.clientWidth);
+ measure();
+ if (typeof ResizeObserver === "undefined") {
+ window.addEventListener("resize", measure);
+ return () => window.removeEventListener("resize", measure);
+ }
+ const ro = new ResizeObserver(measure);
+ ro.observe(node);
+ return () => ro.disconnect();
+ }, []);
+
+ const points = React.useMemo(
+ () =>
+ plans
+ .map((plan) => {
+ const point = planPoint(plan);
+ return point ? { plan, ...point } : null;
+ })
+ .filter((p): p is { plan: RefactoringPlan; x: number; y: number } => p !== null),
+ [plans],
+ );
+
+ const dropped = plans.length - points.length;
+
+ const geometry = React.useMemo(() => {
+ if (points.length === 0 || width === 0) return null;
+ const W = width;
+ const H = Math.max(320, Math.min(460, Math.round(W * 0.44)));
+ const plotW = W - PAD_L - PAD_R;
+ const plotH = H - PAD_T - PAD_B;
+
+ const xMax = Math.max(...points.map((p) => p.x));
+ const yMax = axisCeiling(Math.max(...points.map((p) => p.y)));
+ // Dependents are heavily right-skewed — a median of 8 against a max of 195
+ // on this repo — so a linear axis crushes most of the field into the left
+ // fifth. Log spreads it without hiding the outlier.
+ const logMax = Math.log(Math.max(xMax, 2));
+ const xScale = (v: number) => PAD_L + (Math.log(Math.max(v, 1)) / logMax) * plotW;
+ const yScale = (v: number) => PAD_T + plotH - (v / yMax) * plotH;
+
+ const xTicks = [1, 3, 10, 30, 100, 300, 1000].filter((t) => t <= xMax);
+ const yTicks = [0, 0.25, 0.5, 0.75, 1].map((f) => Math.round((yMax * f) / 10) * 10);
+
+ return {
+ W,
+ H,
+ plotW,
+ plotH,
+ xScale,
+ yScale,
+ xTicks,
+ yTicks,
+ medianX: median(points.map((p) => p.x)),
+ medianY: median(points.map((p) => p.y)),
+ };
+ }, [points, width]);
+
+ const hovered = points.find((p) => p.plan.id === highlightedId) ?? null;
+
+ const byType = new Map<string, number>();
+ for (const p of points) byType.set(p.plan.refactoring_type, (byType.get(p.plan.refactoring_type) ?? 0) + 1);
+
+ return (
+ <div>
+ <div ref={wrapRef} className="relative">
+ {geometry ? (
+ <svg
+ viewBox={`0 0 ${geometry.W} ${geometry.H}`}
+ height={geometry.H}
+ className="block w-full text-[var(--color-text-primary)]"
+ role="img"
+ aria-label={`${points.length} structural refactoring plans plotted on file size against the number of files that import them. The ranked list below carries the same plans.`}
+ >
+ {geometry.yTicks.map((t) => (
+ <g key={`y-${t}`}>
+ <line
+ x1={PAD_L}
+ y1={geometry.yScale(t)}
+ x2={PAD_L + geometry.plotW}
+ y2={geometry.yScale(t)}
+ stroke="currentColor"
+ strokeOpacity={0.08}
+ />
+ <text
+ x={PAD_L - 9}
+ y={geometry.yScale(t) + 3.5}
+ textAnchor="end"
+ className="fill-[var(--color-text-tertiary)] font-mono text-[10px] tabular-nums"
+ >
+ {formatNumber(t)}
+ </text>
+ </g>
+ ))}
+
+ {geometry.xTicks.map((t) => (
+ <text
+ key={`x-${t}`}
+ x={geometry.xScale(t)}
+ y={PAD_T + geometry.plotH + 18}
+ textAnchor="middle"
+ className="fill-[var(--color-text-tertiary)] font-mono text-[10px] tabular-nums"
+ >
+ {t}
+ </text>
+ ))}
+
+ {/* Medians, so a reader can place a point without reading both axes. */}
+ <line
+ x1={geometry.xScale(geometry.medianX)}
+ y1={PAD_T}
+ x2={geometry.xScale(geometry.medianX)}
+ y2={PAD_T + geometry.plotH}
+ stroke="currentColor"
+ strokeOpacity={0.2}
+ strokeDasharray="4 4"
+ />
+ <line
+ x1={PAD_L}
+ y1={geometry.yScale(geometry.medianY)}
+ x2={PAD_L + geometry.plotW}
+ y2={geometry.yScale(geometry.medianY)}
+ stroke="currentColor"
+ strokeOpacity={0.2}
+ strokeDasharray="4 4"
+ />
+
+ <text
+ x={PAD_L + geometry.plotW / 2}
+ y={geometry.H - 8}
+ textAnchor="middle"
+ className="fill-[var(--color-text-tertiary)] text-[11px]"
+ >
+ Files that import it
+ </text>
+ <text
+ x={14}
+ y={PAD_T + geometry.plotH / 2}
+ textAnchor="middle"
+ transform={`rotate(-90 14 ${PAD_T + geometry.plotH / 2})`}
+ className="fill-[var(--color-text-tertiary)] text-[11px]"
+ >
+ Lines in the file
+ </text>
+
+ {points.map(({ plan, x, y }) => {
+ const cx = geometry.xScale(x) + jitter(plan.id);
+ const cy = geometry.yScale(y);
+ const lit = plan.id === highlightedId;
+ const r = lit ? 7 : 5.2;
+ const path = markPath(plan.refactoring_type, cx, cy, r);
+ const meta = typeMeta(plan.refactoring_type);
+ return (
+ <g
+ key={plan.id}
+ role={onSelect ? "button" : undefined}
+ tabIndex={onSelect ? 0 : undefined}
+ aria-label={`${meta.label}, ${plan.file_path}, ${formatNumber(x)} dependent files, ${formatNumber(y)} lines`}
+ className={onSelect ? "cursor-pointer outline-none" : "outline-none"}
+ onMouseEnter={() => onHighlight?.(plan.id)}
+ onMouseLeave={() => onHighlight?.(null)}
+ onFocus={() => onHighlight?.(plan.id)}
+ onBlur={() => onHighlight?.(null)}
+ onClick={onSelect ? () => onSelect(plan) : undefined}
+ onKeyDown={
+ onSelect
+ ? (e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onSelect(plan);
+ }
+ }
+ : undefined
+ }
+ >
+ {path ? (
+ <path
+ d={path}
+ fill="var(--color-accent-fill)"
+ fillOpacity={lit ? 0.95 : 0.72}
+ />
+ ) : (
+ <circle
+ cx={cx}
+ cy={cy}
+ r={r}
+ fill="var(--color-accent-fill)"
+ fillOpacity={lit ? 0.95 : 0.72}
+ />
+ )}
+ {lit ? (
+ <circle
+ cx={cx}
+ cy={cy}
+ r={r + 4}
+ fill="none"
+ stroke="var(--color-accent-fill)"
+ strokeOpacity={0.5}
+ />
+ ) : null}
+ <circle cx={cx} cy={cy} r={HIT_RADIUS} fill="transparent" />
+ </g>
+ );
+ })}
+ </svg>
+ ) : (
+ <div style={{ height: 320 }} />
+ )}
+
+ {hovered && geometry ? (
+ <MapCard
+ plan={hovered.plan}
+ x={geometry.xScale(hovered.x)}
+ y={geometry.yScale(hovered.y)}
+ width={geometry.W}
+ />
+ ) : null}
+ </div>
+
+ <div className="mt-2.5 flex flex-wrap items-center gap-x-5 gap-y-2 border-t border-[var(--color-border-default)] pt-3">
+ {[...byType.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([type, count]) => (
+ <span
+ key={type}
+ className="inline-flex items-center gap-2 text-xs text-[var(--color-text-secondary)]"
+ >
+ <svg width="13" height="13" aria-hidden className="shrink-0">
+ {markPath(type, 6.5, 6.5, 4.6) ? (
+ <path d={markPath(type, 6.5, 6.5, 4.6)!} fill="var(--color-accent-fill)" fillOpacity={0.8} />
+ ) : (
+ <circle cx="6.5" cy="6.5" r="4.6" fill="var(--color-accent-fill)" fillOpacity={0.8} />
+ )}
+ </svg>
+ {typeMeta(type).label}
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {count}
+ </span>
+ </span>
+ ))}
+ {/* Say the bound. A view that quietly covers part of its subject reads
+ as covering all of it. */}
+ {dropped > 0 ? (
+ <span className="ml-auto text-xs text-[var(--color-text-tertiary)]">
+ {formatNumber(dropped)} not plotted — no size or dependency figures yet
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+/** The hover card, placed from the point's own coordinates. Flips to the other
+ * side near the right edge so it never leaves the plot. */
+function MapCard({
+ plan,
+ x,
+ y,
+ width,
+}: {
+ plan: RefactoringPlan;
+ x: number;
+ y: number;
+ width: number;
+}) {
+ const flip = x > width - 240;
+ const meta = typeMeta(plan.refactoring_type);
+ return (
+ <div
+ className="pointer-events-none absolute z-10 w-[220px] rounded-lg border border-[var(--color-border-hover)] bg-[var(--color-bg-surface)] px-3 py-2 shadow-md"
+ style={{
+ left: flip ? undefined : x + 16,
+ right: flip ? width - x + 16 : undefined,
+ top: Math.max(0, y - 62),
+ }}
+ >
+ <div className="text-[11px] text-[var(--color-text-secondary)]">{meta.label}</div>
+ <div className="mt-0.5 break-all font-mono text-xs font-semibold text-[var(--color-text-primary)]">
+ {plan.file_path.split("/").pop()}
+ </div>
+ <div className="mt-1.5 border-t border-[var(--color-border-default)] pt-1.5 text-[11px] tabular-nums text-[var(--color-text-secondary)]">
+ {formatNumber(plan.file_nloc ?? 0)} lines · {formatNumber(plan.dependents ?? 0)} dependent
+ {(plan.dependents ?? 0) === 1 ? "" : "s"}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 213beb440..65609b3be 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -33,6 +33,18 @@ export interface RefactoringPlan {
confidence: Confidence | string;
source_biomarker: string;
rank_score: number;
+ /**
+ * Files that import this plan's file, and the file's line count. Served
+ * rather than derived: `blast_radius` carries a count under three different
+ * keys depending on the detector, so reading it here produced two different
+ * numbers for the same file.
+ *
+ * Optional so a frontend ahead of its backend degrades — an older server
+ * simply omits them and the structural map renders nothing rather than
+ * plotting every plan at the origin.
+ */
+ dependents?: number;
+ file_nloc?: number;
}
export interface RefactoringTypeCount {
@@ -523,3 +535,124 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {
}
return wins;
}
+
+// ── Structural vs local ───────────────────────────────────────────────────
+
+/**
+ * The types that change a file's shape rather than its insides.
+ *
+ * This split is what the surface is organised around, and it came from the
+ * distribution rather than from taste: on a real index Extract Helper and
+ * Extract Method are 96% of all plans and 89% of everything is rated small
+ * effort, so "all plans" is overwhelmingly a list of local tidy-ups you do
+ * while you are already in the file. The rest change how the codebase is laid
+ * out, are worth planning, and are few enough to rank by hand.
+ */
+export const STRUCTURAL_TYPES: readonly RefactoringType[] = [
+ "split_file",
+ "break_cycle",
+ "extract_class",
+ "move_method",
+];
+
+export function isStructural(plan: RefactoringPlan): boolean {
+ return (STRUCTURAL_TYPES as readonly string[]).includes(plan.refactoring_type);
+}
+
+/** A plan's coordinates on the structural map, or null when either figure is
+ * missing. 0 means "not measured" for both — a repo with no health pass has no
+ * line counts, and plotting those at the origin would invent a cluster. */
+export function planPoint(plan: RefactoringPlan): { x: number; y: number } | null {
+ const x = plan.dependents ?? 0;
+ const y = plan.file_nloc ?? 0;
+ return x > 0 && y > 0 ? { x, y } : null;
+}
+
+/**
+ * Below this many plottable points the map is not worth its height: a scatter
+ * with four dots asks the reader to decode two axes to learn less than four
+ * rows would tell them. The section falls back to rows only.
+ */
+export const MAP_MIN_POINTS = 8;
+
+/**
+ * The evidence behind a plan, as one sentence.
+ *
+ * `planSynopsis` says what the plan *is* ("Split into 6 modules"). This says
+ * why it was proposed, in the numbers the detector actually recorded, because
+ * the ranked plans at the top of the page are the ones a reader has to decide
+ * about rather than skim. Returns "" when the evidence dict is empty, so a
+ * caller renders nothing rather than an empty clause.
+ */
+export function planReason(plan: RefactoringPlan): string {
+ const ev = plan.evidence ?? {};
+ const num = (key: string): number => Number(ev[key] ?? 0);
+
+ switch (plan.refactoring_type) {
+ case "split_file": {
+ const parts: string[] = [];
+ const nloc = num("file_nloc");
+ const symbols = num("symbol_count");
+ const groups = num("group_count") || splitGroups(plan).length;
+ if (nloc && symbols && groups) {
+ parts.push(
+ `${nloc.toLocaleString()} lines and ${symbols} symbols that fall into ${groups} groups the imports already respect`,
+ );
+ }
+ const cut = num("cut_edges");
+ const intra = num("intra_edges");
+ if (intra) {
+ parts.push(
+ cut === 0
+ ? `No edges cross a seam`
+ : `${cut} of ${intra} internal edges cross a seam`,
+ );
+ }
+ const cochange = num("cochange_edges");
+ if (cochange) parts.push(`${cochange} pairs of these symbols keep changing together`);
+ return parts.join(". ") + (parts.length ? "." : "");
+ }
+ case "break_cycle": {
+ const size = num("cycle_size") || cycleMembers(plan).length;
+ const edges = num("edge_count");
+ const cuts = num("cut_count") || cutEdges(plan).length;
+ if (!size) return "";
+ return `${size} modules import each other in a ring${
+ edges ? ` across ${edges} edges` : ""
+ }. ${cuts} cut${cuts === 1 ? "" : "s"} open${cuts === 1 ? "s" : ""} it.`;
+ }
+ case "extract_class": {
+ const methods = num("method_count");
+ const fields = num("field_count");
+ const lcom = num("lcom4");
+ if (!methods) return "";
+ return `${methods} methods and ${fields} fields in one class, splitting into ${
+ lcom || 2
+ } groups that share no state.`;
+ }
+ case "move_method": {
+ const foreign = num("foreign_calls");
+ const own = num("own_calls");
+ if (!foreign) return "";
+ return `Reaches into the other class ${foreign} times against ${own} call${
+ own === 1 ? "" : "s"
+ } to its own.`;
+ }
+ case "extract_method": {
+ const slice = num("slice_nloc");
+ const ccn = num("ccn_removed");
+ if (!slice) return "";
+ return `${slice} lines doing one separable job${
+ ccn ? `, carrying ${ccn} of the function's decision points` : ""
+ }.`;
+ }
+ case "extract_helper": {
+ const occ = num("occurrence_count") || extractHelperOccurrences(plan).length;
+ const lines = num("duplicated_lines");
+ if (!occ) return "";
+ return `The same ${lines ? `${lines}-line ` : ""}block appears at ${occ} sites.`;
+ }
+ default:
+ return "";
+ }
+}
diff --git a/packages/ui/src/ui/sheet.tsx b/packages/ui/src/ui/sheet.tsx
index b51c77542..f7ff782c2 100644
--- a/packages/ui/src/ui/sheet.tsx
+++ b/packages/ui/src/ui/sheet.tsx
@@ -30,12 +30,17 @@ SheetOverlay.displayName = "SheetOverlay";
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
side?: "left" | "right";
+ /** Accessible name for the close button. Defaults to the navigation wording
+ * this component was written for; pass it when the sheet holds something
+ * else, so a screen reader is not told to "close navigation" on a detail
+ * panel. */
+ closeLabel?: string;
}
const SheetContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
SheetContentProps
->(({ className, children, side = "left", ...props }, ref) => (
+>(({ className, children, side = "left", closeLabel = "Close navigation", ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<DialogPrimitive.Content
@@ -64,7 +69,7 @@ const SheetContent = React.forwardRef<
"hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--color-accent-primary)]",
"disabled:pointer-events-none",
)}
- aria-label="Close navigation"
+ aria-label={closeLabel}
>
<X className="h-5 w-5" />
</DialogPrimitive.Close>
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index fe4db2340..4727d7a5e 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -3,21 +3,29 @@
/**
* 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, Split
- * File). 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.
+ * The deterministic refactoring plans the health pass writes. The page leads
+ * with what the pile actually is (mostly small, local extractions), then the
+ * handful that change the codebase's shape, then everything as rows.
+ *
+ * Two URL params, both shareable: `?type=` filters the list, `?plan=` opens one
+ * plan's drawer. The plan param is what the old centred modal could not have —
+ * a plan you can send to someone.
*/
import { use, useCallback, useMemo, useState } from "react";
import useSWR from "swr";
-import { parseAsStringLiteral, useQueryState } from "nuqs";
+import { parseAsString, 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 {
+ RefactoringBoard,
+ RefactoringDrawer,
+ STRUCTURAL_TYPES,
+ 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 {
@@ -27,7 +35,7 @@ import {
type RefactoringSettings,
} from "@/lib/api/refactoring";
-const TYPE_VALUES = ["all", ...TYPE_ORDER] as const;
+const TYPE_VALUES = ["all", "structural", ...TYPE_ORDER] as const;
type TypeFilter = (typeof TYPE_VALUES)[number];
export default function RefactoringPage({ params }: { params: Promise<{ id: string }> }) {
@@ -36,6 +44,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
"type",
parseAsStringLiteral(TYPE_VALUES).withDefault("all"),
);
+ const [openPlanId, setOpenPlanId] = useQueryState("plan", parseAsString);
const { data, error, isLoading, mutate } = useSWR<RefactoringTargets>(
`refactoring:${repoId}`,
@@ -43,15 +52,28 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
{ revalidateOnFocus: false },
);
+ const allPlans = useMemo(() => data?.plans ?? [], [data?.plans]);
+
const filtered = useMemo(() => {
- const plans = data?.plans ?? [];
- return type === "all" ? plans : plans.filter((p) => p.refactoring_type === type);
- }, [data?.plans, type]);
+ if (type === "all") return allPlans;
+ if (type === "structural") {
+ return allPlans.filter((p) =>
+ (STRUCTURAL_TYPES as readonly string[]).includes(p.refactoring_type),
+ );
+ }
+ return allPlans.filter((p) => p.refactoring_type === type);
+ }, [allPlans, type]);
const prefix = `/repos/${repoId}`;
- const fileHref = (path: string) => fileEntityPath(prefix, path);
+ const fileHref = useCallback((path: string) => fileEntityPath(prefix, path), [prefix]);
+
+ // The open plan comes from the URL, so a reload or a shared link lands on the
+ // same drawer rather than the top of the list.
+ const openPlan = useMemo(
+ () => allPlans.find((p) => p.id === openPlanId) ?? null,
+ [allPlans, openPlanId],
+ );
- // 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), []);
@@ -72,20 +94,21 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
);
const counts = new Map((data?.summary.by_type ?? []).map((c) => [c.type, c.count]));
+ const structuralCount = (STRUCTURAL_TYPES as readonly string[]).reduce(
+ (n, t) => n + (counts.get(t) ?? 0),
+ 0,
+ );
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,
- })),
+ { id: "structural" as const, label: "Structural", badge: structuralCount },
+ ...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."
+ description="Concrete, ranked plans the health pass wrote from your code. Open one to see the change, or hand it to a coding agent."
actions={
<button
type="button"
@@ -110,26 +133,40 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
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)]"
- />
- ))}
+ // Matches the real layout's shapes: a lede block, a ribbon, a field.
+ <div className="space-y-8">
+ <div className="h-32 animate-pulse rounded-xl bg-[var(--color-bg-surface)]" />
+ <div className="h-16 animate-pulse rounded-xl bg-[var(--color-bg-surface)]" />
+ <div className="h-72 animate-pulse rounded-xl bg-[var(--color-bg-surface)]" />
</div>
) : (
<RefactoringBoard
plans={filtered}
- summary={data?.summary}
+ allPlans={allPlans}
+ onOpen={(plan) => void setOpenPlanId(plan.id)}
onAiPrompt={onAiPrompt}
- onGenerateCode={onGenerateCode}
- settingsHref={`${prefix}/settings`}
+ onSeeStructural={() => void setType("structural")}
fileHref={fileHref}
+ // The lede and Start here describe the whole repo, so they only
+ // belong on the unfiltered view — under a type filter they would
+ // be talking about a set the list below is not showing.
+ showLede={type === "all"}
/>
)}
</div>
+ <RefactoringDrawer
+ plan={openPlan}
+ open={openPlan !== null}
+ onOpenChange={(open) => {
+ if (!open) void setOpenPlanId(null);
+ }}
+ onAiPrompt={onAiPrompt}
+ onGenerateCode={onGenerateCode}
+ settingsHref={`${prefix}/settings`}
+ fileHref={fileHref}
+ />
+
<AiPromptModal
open={promptPlan !== null}
onOpenChange={(open) => {
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 9cf8f3640..46cd1c98b 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -223,9 +223,7 @@ async def test_type_filter_narrows_plans_but_keeps_summary(client: AsyncClient,
assert body["summary"]["total"] == 4
-async def test_file_path_filter_narrows_plans_but_keeps_summary(
- client: AsyncClient, app
-) -> None:
+async def test_file_path_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",
@@ -310,6 +308,79 @@ async def test_centrality_breaks_ties_in_ranking(client: AsyncClient, app) -> No
assert body["plans"][0]["rank_score"] > body["plans"][1]["rank_score"]
+async def test_plot_fields_come_from_centrality_and_health(client: AsyncClient, app) -> None:
+ """`dependents` and `file_nloc` are served, and both read one source per
+ figure. `dependents` is the in-degree the ranking already uses, so two plans
+ on the same file agree even though their blast-radius dicts carry the count
+ under different keys — the drift that made a scatter axis untrustworthy."""
+ 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}}
+ )
+ await crud.save_health_metrics(
+ session,
+ repo_id,
+ [
+ {
+ "file_path": "pkg/hub.py",
+ "score": 4.0,
+ "max_ccn": 9,
+ "max_nesting": 3,
+ "nloc": 812,
+ "has_test_file": False,
+ "module": "pkg",
+ }
+ ],
+ )
+ common = {
+ "file_path": "pkg/hub.py",
+ "target_symbol": "C",
+ "plan": {},
+ "evidence": {},
+ "impact_delta": 0.0,
+ "effort_bucket": "M",
+ "confidence": "medium",
+ "source_biomarker": "",
+ }
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ # Two detectors, two different blast-radius spellings.
+ {
+ **common,
+ "refactoring_type": "extract_class",
+ "blast_radius": {"dependents_count": 9},
+ },
+ {**common, "refactoring_type": "break_cycle", "blast_radius": {"callers": 3}},
+ ],
+ )
+ await session.commit()
+
+ plans = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]
+ assert len(plans) == 2
+ assert {p["dependents"] for p in plans} == {25}
+ assert {p["file_nloc"] for p in plans} == {812}
+
+ # The single-plan endpoint agrees with the list it was opened from.
+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/{plans[0]['id']}")).json()
+ assert detail["dependents"] == 25
+ assert detail["file_nloc"] == 812
+
+
+async def test_plot_fields_default_to_zero_without_a_health_pass(client: AsyncClient, app) -> None:
+ """A repo with plans but no health snapshot still serves the fields. 0 is a
+ real answer here — the surface reads it as "not measured" and drops the
+ plan from the chart rather than plotting it at the origin."""
+ repo_id = await _seed(client, app)
+ plans = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]
+ assert plans
+ assert all(p["file_nloc"] == 0 for p in plans)
+ assert all(p["dependents"] == 0 for p in plans)
+
+
async def test_min_confidence_filters(client: AsyncClient, app) -> None:
repo_id = await _seed(client, app)
resp = await client.get(