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): generate code from plans with a diff viewer (#594)

Raghav Chamadiya759d1d5fea60
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
index 9423e9717..3a650ee84 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
@@ -143,12 +143,38 @@ def _collect_self_members(method_node: Node, lmap: LanguageNodeMap) -> set[str]:
return members
+def _tcc(field_sets: list[set[str]]) -> float:
+ """Tight Class Cohesion (Bieman-Kang): the fraction of method pairs that
+ share at least one instance field, in ``[0, 1]``.
+
+ *field_sets* is the per-method set of instance fields (method names already
+ excluded). Returns ``1.0`` ("no signal") when there are fewer than two
+ methods, so an unparsed/fieldless class never reads as low-cohesion — the
+ same posture as the LCOM4 safety valve.
+ """
+ n = len(field_sets)
+ if n < 2:
+ return 1.0
+ possible = n * (n - 1) // 2
+ if possible == 0:
+ return 1.0
+ connected = 0
+ for i in range(n):
+ fi = field_sets[i]
+ if not fi:
+ continue
+ for j in range(i + 1, n):
+ if fi & field_sets[j]:
+ connected += 1
+ return connected / possible
+
+
def _compute_lcom4(
method_nodes: list[Node],
method_fcs: list[FunctionComplexity],
lmap: LanguageNodeMap,
-) -> tuple[int, int, list[CohesionGroup]]:
- """Return ``(lcom4, field_count, components)`` for a class.
+) -> tuple[int, int, list[CohesionGroup], float]:
+ """Return ``(lcom4, field_count, components, tcc)`` for a class.
LCOM4 = number of connected components over the methods, where two
methods are connected if they share an instance member or one calls
@@ -167,7 +193,7 @@ def _compute_lcom4(
"""
n = len(method_nodes)
if n == 0:
- return 1, 0, []
+ return 1, 0, [], 1.0
members_per_method: list[set[str]] = [
_collect_self_members(node, lmap) for node in method_nodes
@@ -177,8 +203,12 @@ def _compute_lcom4(
all_members: set[str] = set().union(*members_per_method) if members_per_method else set()
field_count = len(all_members - method_names)
+ # TCC over instance fields only (method-call edges don't count toward it),
+ # so it complements LCOM4 rather than restating it.
+ tcc = _tcc([members - method_names for members in members_per_method])
+
if total_refs == 0:
- return 1, field_count, []
+ return 1, field_count, [], tcc
# Union-find over method indices.
parent = list(range(n))
@@ -243,7 +273,7 @@ def _compute_lcom4(
)
indexed_groups.sort(key=lambda pair: _pos(pair[0]))
groups = [g for _, g in indexed_groups]
- return len(components), field_count, groups
+ return len(components), field_count, groups, tcc
def _collect_classes(
@@ -262,7 +292,7 @@ def _collect_classes(
# Keep nodes and FCs aligned (a method missing from the function
# pass — unusual — drops out of both).
aligned_nodes = [m for m in method_nodes if m.id in fc_by_node_id]
- lcom4, field_count, components = _compute_lcom4(aligned_nodes, method_fcs, lmap)
+ lcom4, field_count, components, tcc = _compute_lcom4(aligned_nodes, method_fcs, lmap)
classes.append(
ClassComplexity(
name=_class_name(class_node),
@@ -275,6 +305,7 @@ def _collect_classes(
max_method_ccn=max((fc.ccn for fc in method_fcs), default=0),
field_count=field_count,
components=components,
+ tcc=tcc,
)
)
return classes
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index e752a4cff..0b4acdcae 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -106,6 +106,13 @@ class ClassComplexity:
max_method_ccn: int = 0
field_count: int = 0
components: list[CohesionGroup] = field(default_factory=list)
+ # Tight Class Cohesion (Bieman-Kang): the fraction of method pairs that
+ # share at least one instance field, in ``[0, 1]`` — higher is more
+ # cohesive. ``1.0`` is the "no signal" default (fewer than two methods, or
+ # a language whose member access we do not map), mirroring the ``lcom4``
+ # safety valve. A cohesive Extract Class split raises the worst split
+ # class's TCC toward ``1``; the enrich self-check reads it before/after.
+ tcc: float = 1.0
@dataclass(frozen=True)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
index df3747c24..ce349d996 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
@@ -109,6 +109,7 @@ class ExtractClassDetector(RefactoringDetector):
"method_count": cls.method_count,
"field_count": cls.field_count,
"wmc": wmc,
+ "tcc": round(float(getattr(cls, "tcc", 1.0)), 3),
},
impact_delta=round(float(impact_delta), 3),
effort_bucket=effort_bucket(cls.total_nloc),
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index e5a6e5222..cb471cb1c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -105,19 +105,22 @@ class EnrichmentResult:
def llm_enrichment_enabled(config: dict[str, Any]) -> bool:
- """Whether ``refactoring.llm.enabled`` is set in a loaded repo config.
-
- Off by default. The CLI's explicit ``--generate-code`` flag is its own
- opt-in and does not consult this; the server/MCP surfaces gate on it so a
- hosted deployment never exposes code-gen unless the repo enabled it.
+ """Whether code generation is enabled for this repo (``refactoring.llm.enabled``).
+
+ Enabled unless the repo explicitly turns it off — an unset key means on.
+ Code generation never runs during indexing and only ever fires on an
+ explicit request (a button click / CLI flag / MCP call), and the web + MCP
+ surfaces both require a local checkout (they 404 without one), so defaulting
+ on simply makes the local-``serve`` experience work without a config trip;
+ a repo can still set ``refactoring.llm.enabled: false`` to disable it.
"""
refactoring = config.get("refactoring")
if not isinstance(refactoring, dict):
- return False
+ return True
llm = refactoring.get("llm")
if not isinstance(llm, dict):
- return False
- return bool(llm.get("enabled", False))
+ return True
+ return bool(llm.get("enabled", True))
def build_enrichment_provider(
@@ -485,8 +488,15 @@ def _validate_extract_class(
return {"status": "skipped", "reason": "no classes parsed from response"}
before = evidence.get("lcom4") if isinstance(evidence, dict) else None
- after = [{"name": c.name, "lcom4": c.lcom4} for c in classes]
+ before_tcc = evidence.get("tcc") if isinstance(evidence, dict) else None
+ after = [
+ {"name": c.name, "lcom4": c.lcom4, "tcc": round(float(getattr(c, "tcc", 1.0)), 3)}
+ for c in classes
+ ]
after_max = max((c.lcom4 for c in classes), default=None)
+ # The split's weakest class drives the TCC verdict — every extracted class
+ # should be cohesive (TCC near 1), so the minimum is the honest floor.
+ after_min_tcc = min((float(getattr(c, "tcc", 1.0)) for c in classes), default=None)
improved = (
isinstance(before, int)
and after_max is not None
@@ -496,8 +506,10 @@ def _validate_extract_class(
return {
"status": "checked",
"before_lcom4": before,
+ "before_tcc": before_tcc,
"after_classes": after,
"after_max_lcom4": after_max,
+ "after_min_tcc": None if after_min_tcc is None else round(after_min_tcc, 3),
"class_count": len(classes),
"improved": bool(improved),
}
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 317035343..662f09565 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -207,6 +207,107 @@ async def get_refactoring_targets(
)
+# ---------------------------------------------------------------------------
+# Code-gen settings — read/write the refactoring.llm config block. Declared
+# before the dynamic /{suggestion_id} GET so the static `settings` path wins.
+# ---------------------------------------------------------------------------
+
+
+class RefactoringSettings(BaseModel):
+ """The opt-in code-generation switches, mirrored from ``refactoring.llm``."""
+
+ enabled: bool = False
+ provider: str | None = None
+ model: str | None = None
+
+
+def _read_refactoring_settings(config: dict[str, Any]) -> RefactoringSettings:
+ """Project ``refactoring.llm`` out of a loaded config, tolerant of shape.
+
+ ``enabled`` defaults to ``True`` when unset, matching
+ :func:`llm_enrichment_enabled` — an untouched repo shows the toggle on.
+ """
+ refactoring = config.get("refactoring")
+ llm = refactoring.get("llm") if isinstance(refactoring, dict) else None
+ if not isinstance(llm, dict):
+ return RefactoringSettings(enabled=True)
+ provider = llm.get("provider")
+ model = llm.get("model")
+ return RefactoringSettings(
+ enabled=bool(llm.get("enabled", True)),
+ provider=provider if isinstance(provider, str) and provider else None,
+ model=model if isinstance(model, str) and model else None,
+ )
+
+
+async def _local_repo_path(session: AsyncSession, repo_id: str) -> Path:
+ """The repo's on-disk checkout, or a 404 — code-gen settings are a
+ local-``serve`` capability (they live in the repo's ``.repowise``)."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None or not repo.local_path:
+ raise HTTPException(status_code=404, detail=f"repository not found: {repo_id}")
+ repo_path = Path(repo.local_path)
+ if not repo_path.exists():
+ raise HTTPException(
+ status_code=404, detail="repository checkout not accessible on this server"
+ )
+ return repo_path
+
+
[email protected]("/{repo_id}/refactoring/settings", response_model=RefactoringSettings)
+async def get_refactoring_settings(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> RefactoringSettings:
+ """Current ``refactoring.llm`` settings for the repo (enabled + provider/model)."""
+ from repowise.core.repo_config import load_repo_config
+
+ repo_path = await _local_repo_path(session, repo_id)
+ return _read_refactoring_settings(load_repo_config(repo_path))
+
+
[email protected]("/{repo_id}/refactoring/settings", response_model=RefactoringSettings)
+async def update_refactoring_settings(
+ repo_id: str,
+ body: RefactoringSettings,
+ session: AsyncSession = Depends(get_db_session),
+) -> RefactoringSettings:
+ """Persist the ``refactoring.llm`` block to the repo's ``.repowise/config.yaml``.
+
+ Round-trips through the loaded config so unrelated keys are preserved, then
+ writes only the ``refactoring.llm.{enabled,provider,model}`` sub-tree. A
+ blank provider/model clears that key rather than writing an empty string.
+ """
+ from repowise.core.repo_config import load_repo_config, save_repo_config
+
+ repo_path = await _local_repo_path(session, repo_id)
+ config = load_repo_config(repo_path)
+
+ refactoring = config.get("refactoring")
+ if not isinstance(refactoring, dict):
+ refactoring = {}
+ config["refactoring"] = refactoring
+ llm = refactoring.get("llm")
+ if not isinstance(llm, dict):
+ llm = {}
+ refactoring["llm"] = llm
+
+ llm["enabled"] = bool(body.enabled)
+ provider = (body.provider or "").strip()
+ model = (body.model or "").strip()
+ if provider:
+ llm["provider"] = provider
+ else:
+ llm.pop("provider", None)
+ if model:
+ llm["model"] = model
+ else:
+ llm.pop("model", None)
+
+ save_repo_config(repo_path, config)
+ return _read_refactoring_settings(config)
+
+
@router.get("/{repo_id}/refactoring/{suggestion_id}", response_model=RefactoringPlanResponse)
async def get_refactoring_plan(
repo_id: str,
diff --git a/packages/ui/src/refactoring/diff-view.tsx b/packages/ui/src/refactoring/diff-view.tsx
new file mode 100644
index 000000000..eb1a73cca
--- /dev/null
+++ b/packages/ui/src/refactoring/diff-view.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import * as React from "react";
+
+/**
+ * A self-contained unified-diff renderer for the generated-code panel.
+ *
+ * It parses a git-style unified diff (`--- a/path`, `+++ b/path`, `@@` hunks)
+ * into per-file blocks and colorizes added / removed / context / header lines.
+ * Pure presentation, no dependencies — so the hosted frontend can reuse it as
+ * is. Unparseable input degrades to a plain monospace block.
+ */
+
+type DiffLineKind = "add" | "del" | "hunk" | "meta" | "context";
+
+interface DiffLine {
+ kind: DiffLineKind;
+ text: string;
+}
+
+interface DiffFile {
+ /** The b-side path (new file), falling back to the a-side. */
+ path: string;
+ lines: DiffLine[];
+ added: number;
+ removed: number;
+}
+
+function classifyLine(text: string): DiffLineKind {
+ if (text.startsWith("@@")) return "hunk";
+ if (
+ text.startsWith("diff ") ||
+ text.startsWith("index ") ||
+ text.startsWith("--- ") ||
+ text.startsWith("+++ ") ||
+ text.startsWith("new file") ||
+ text.startsWith("deleted file") ||
+ text.startsWith("similarity ") ||
+ text.startsWith("rename ")
+ ) {
+ return "meta";
+ }
+ if (text.startsWith("+")) return "add";
+ if (text.startsWith("-")) return "del";
+ return "context";
+}
+
+function stripPathPrefix(raw: string): string {
+ // `+++ b/pkg/x.py` → `pkg/x.py`; tolerate a missing a//b/ prefix.
+ const path = raw.replace(/^[+-]{3}\s+/, "").trim();
+ if (path === "/dev/null") return path;
+ return path.replace(/^[ab]\//, "");
+}
+
+/** Split a unified diff into per-file blocks with add/remove tallies. */
+export function parseUnifiedDiff(diff: string): DiffFile[] {
+ const files: DiffFile[] = [];
+
+ const open = (path: string): DiffFile => {
+ const file: DiffFile = { path, lines: [], added: 0, removed: 0 };
+ files.push(file);
+ return file;
+ };
+
+ const last = (): DiffFile => files[files.length - 1] ?? open("");
+
+ for (const rawText of diff.split("\n")) {
+ const text = rawText.replace(/\r$/, "");
+ const kind = classifyLine(text);
+
+ if (text.startsWith("diff ") || text.startsWith("+++ ")) {
+ const path = text.startsWith("+++ ")
+ ? stripPathPrefix(text)
+ : text.replace(/^diff\s+--git\s+/, "");
+ const cur = files[files.length - 1];
+ if (text.startsWith("+++ ") && cur && cur.lines.length === 0) {
+ cur.path = path; // refine the path from the +++ header
+ } else if (!cur || cur.lines.length > 0) {
+ open(path);
+ }
+ }
+
+ const file = last();
+ file.lines.push({ kind, text });
+ if (kind === "add") file.added += 1;
+ else if (kind === "del") file.removed += 1;
+ }
+
+ // Drop a leading empty synthetic file if the diff started mid-content.
+ return files.filter((f) => f.lines.length > 0);
+}
+
+const LINE_CLASS: Record<DiffLineKind, string> = {
+ add: "bg-[var(--color-success)]/10 text-[var(--color-text-primary)]",
+ del: "bg-[var(--color-error)]/10 text-[var(--color-text-primary)]",
+ hunk: "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]",
+ meta: "text-[var(--color-text-tertiary)]",
+ context: "text-[var(--color-text-secondary)]",
+};
+
+export interface DiffViewProps {
+ diff: string;
+ /** When the diff is empty, render this instead (e.g. the raw content). */
+ emptyFallback?: React.ReactNode;
+}
+
+export function DiffView({ diff, emptyFallback }: DiffViewProps) {
+ const files = React.useMemo(() => parseUnifiedDiff(diff), [diff]);
+
+ if (!diff.trim() || files.length === 0) {
+ return <>{emptyFallback ?? null}</>;
+ }
+
+ return (
+ <div className="space-y-3">
+ {files.map((file, i) => (
+ <div
+ key={`${file.path}-${i}`}
+ className="overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ >
+ <div className="flex items-center justify-between gap-3 border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-1.5">
+ <span className="truncate font-mono text-xs text-[var(--color-text-primary)]" title={file.path}>
+ {file.path || "(diff)"}
+ </span>
+ <span className="shrink-0 font-mono text-[11px] tabular-nums">
+ <span className="text-[var(--color-success)]">+{file.added}</span>{" "}
+ <span className="text-[var(--color-error)]">-{file.removed}</span>
+ </span>
+ </div>
+ <pre className="overflow-x-auto px-0 py-1 text-[12px] leading-[1.5]">
+ <code className="block">
+ {file.lines.map((line, j) => (
+ <span key={j} className={`block px-3 ${LINE_CLASS[line.kind]}`}>
+ {line.text || " "}
+ </span>
+ ))}
+ </code>
+ </pre>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/generate-code-panel.tsx b/packages/ui/src/refactoring/generate-code-panel.tsx
new file mode 100644
index 000000000..4da4f5324
--- /dev/null
+++ b/packages/ui/src/refactoring/generate-code-panel.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import * as React from "react";
+import { Check, Copy, Loader2, RotateCw, Sparkles, TriangleAlert, Wand2 } from "lucide-react";
+import { DiffView } from "./diff-view";
+import {
+ generatedVerdict,
+ type GeneratedCode,
+ type RefactoringPlan,
+ type VerdictTone,
+} from "./types";
+
+/**
+ * Run the opt-in LLM code generation for one plan: takes a deterministic plan,
+ * returns the model's refactored code as a unified diff plus a self-check
+ * verdict. The host supplies {@link GenerateCodePanelProps.onGenerate} (it owns
+ * the API call); this component owns the async state, the diff rendering, and
+ * the copy affordance. No auto-apply — the diff is the wedge.
+ *
+ * All of the logic lives here in the shared package so the hosted frontend
+ * reuses it by passing a different `onGenerate`.
+ */
+export interface GenerateCodePanelProps {
+ plan: RefactoringPlan;
+ /** POST the generate-code endpoint and resolve the result. Host-owned. */
+ onGenerate: (plan: RefactoringPlan) => Promise<GeneratedCode>;
+}
+
+type State =
+ | { status: "idle" }
+ | { status: "loading" }
+ | { status: "done"; result: GeneratedCode }
+ | { status: "error"; message: string };
+
+const VERDICT_STYLE: Record<VerdictTone, string> = {
+ pass: "border-[var(--color-success)]/30 bg-[var(--color-success)]/10 text-[var(--color-success)]",
+ fail: "border-[var(--color-caution)]/30 bg-[var(--color-caution)]/10 text-[var(--color-caution)]",
+ neutral:
+ "border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)]",
+};
+
+export function GenerateCodePanel({ plan, onGenerate }: GenerateCodePanelProps) {
+ const [state, setState] = React.useState<State>({ status: "idle" });
+
+ // A plan is identified by its id; reset when the host swaps the plan so the
+ // panel never shows a stale diff for a different suggestion.
+ React.useEffect(() => {
+ setState({ status: "idle" });
+ }, [plan.id]);
+
+ const run = React.useCallback(async () => {
+ setState({ status: "loading" });
+ try {
+ const result = await onGenerate(plan);
+ setState({ status: "done", result });
+ } catch (err) {
+ const message =
+ err instanceof Error ? err.message : "Code generation failed. Check the provider config.";
+ setState({ status: "error", message });
+ }
+ }, [onGenerate, plan]);
+
+ if (state.status === "idle") {
+ return (
+ <button
+ type="button"
+ onClick={run}
+ className="inline-flex items-center gap-2 rounded-lg border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-3.5 py-2 text-sm font-semibold text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-primary)] hover:text-[var(--color-bg-surface)]"
+ >
+ <Wand2 className="h-4 w-4" />
+ Generate code
+ </button>
+ );
+ }
+
+ if (state.status === "loading") {
+ return (
+ <div className="flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--color-accent-primary)]" />
+ Generating the refactored code…
+ </div>
+ );
+ }
+
+ if (state.status === "error") {
+ return (
+ <div className="space-y-2.5">
+ <div className="flex items-start gap-2 rounded-lg border border-[var(--color-error)]/30 bg-[var(--color-error)]/5 px-3 py-2.5 text-sm text-[var(--color-text-secondary)]">
+ <TriangleAlert className="mt-0.5 h-4 w-4 shrink-0 text-[var(--color-error)]" />
+ <span>{state.message}</span>
+ </div>
+ <button
+ type="button"
+ onClick={run}
+ className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs font-semibold text-[var(--color-accent-primary)] transition-colors hover:bg-[var(--color-accent-muted)]"
+ >
+ <RotateCw className="h-3.5 w-3.5" />
+ Try again
+ </button>
+ </div>
+ );
+ }
+
+ return <GeneratedResult result={state.result} onRegenerate={run} />;
+}
+
+function GeneratedResult({
+ result,
+ onRegenerate,
+}: {
+ result: GeneratedCode;
+ onRegenerate: () => void;
+}) {
+ const verdict = generatedVerdict(result);
+ const tokens = result.input_tokens + result.output_tokens;
+
+ return (
+ <div className="space-y-3">
+ {/* meta row — provider/model, cache, tokens, self-check verdict */}
+ <div className="flex flex-wrap items-center gap-2">
+ <span 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)]">
+ <Sparkles className="h-3.5 w-3.5 text-[var(--color-accent-primary)]" />
+ {result.provider}
+ {result.model ? <span className="text-[var(--color-text-tertiary)]">· {result.model}</span> : null}
+ </span>
+ {result.cached ? (
+ <span className="rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1 text-xs text-[var(--color-text-tertiary)]">
+ cached
+ </span>
+ ) : tokens > 0 ? (
+ <span className="rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1 text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {tokens.toLocaleString()} tokens
+ </span>
+ ) : null}
+ {verdict ? (
+ <span
+ className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium ${VERDICT_STYLE[verdict.tone]}`}
+ title={verdict.detail}
+ >
+ {verdict.tone === "pass" ? <Check className="h-3.5 w-3.5" /> : null}
+ {verdict.label}
+ {verdict.detail ? (
+ <span className="font-normal opacity-80">· {verdict.detail}</span>
+ ) : null}
+ </span>
+ ) : null}
+ <div className="ml-auto flex items-center gap-1.5">
+ <CopyButton text={result.diff || result.content} />
+ <button
+ type="button"
+ onClick={onRegenerate}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)]"
+ title="Generate again (bypasses the cache on the server only if the plan changed)"
+ >
+ <RotateCw className="h-3.5 w-3.5" />
+ Regenerate
+ </button>
+ </div>
+ </div>
+
+ {/* the diff (or the raw response if the model emitted no diff fence) */}
+ <DiffView
+ diff={result.diff}
+ emptyFallback={
+ <pre className="max-h-[480px] overflow-auto rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 text-[12px] leading-relaxed text-[var(--color-text-secondary)]">
+ {result.content || "The model returned no code."}
+ </pre>
+ }
+ />
+
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ Suggestion only — review the diff and apply it yourself or hand it to your coding agent.
+ </p>
+ </div>
+ );
+}
+
+function CopyButton({ text }: { text: string }) {
+ const [copied, setCopied] = React.useState(false);
+
+ const copy = React.useCallback(() => {
+ if (!text) return;
+ void navigator.clipboard?.writeText(text).then(() => {
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1600);
+ });
+ }, [text]);
+
+ return (
+ <button
+ type="button"
+ onClick={copy}
+ disabled={!text}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-strong)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
+ >
+ {copied ? <Check className="h-3.5 w-3.5 text-[var(--color-success)]" /> : <Copy className="h-3.5 w-3.5" />}
+ {copied ? "Copied" : "Copy diff"}
+ </button>
+ );
+}
diff --git a/packages/ui/src/refactoring/index.ts b/packages/ui/src/refactoring/index.ts
index d5c7d4036..0d448bada 100644
--- a/packages/ui/src/refactoring/index.ts
+++ b/packages/ui/src/refactoring/index.ts
@@ -3,7 +3,10 @@ export * from "./meta";
export * from "./plan-detail";
export * from "./plan-before";
export * from "./plan-comparison";
+export * from "./diff-view";
+export * from "./generate-code-panel";
export * from "./refactoring-plan-card";
export * from "./refactoring-quadrant";
export * from "./refactoring-modal";
+export * from "./refactoring-settings-card";
export * from "./refactoring-board";
diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsx
index 48143e950..41451ec6a 100644
--- a/packages/ui/src/refactoring/refactoring-board.tsx
+++ b/packages/ui/src/refactoring/refactoring-board.tsx
@@ -7,7 +7,14 @@ 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 { blastCount, type Confidence, type EffortBucket, type RefactoringPlan, type RefactoringSummary } from "./types";
+import {
+ blastCount,
+ type Confidence,
+ type EffortBucket,
+ type GeneratedCode,
+ type RefactoringPlan,
+ type RefactoringSummary,
+} from "./types";
const PAGE_SIZE = 60;
@@ -30,6 +37,11 @@ export interface RefactoringBoardProps {
summary?: RefactoringSummary;
/** Open the AI-prompt modal for a plan (host owns the modal + flavor). */
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;
@@ -47,6 +59,8 @@ export function RefactoringBoard({
plans,
summary,
onAiPrompt,
+ onGenerateCode,
+ settingsHref,
fileHref,
showQuadrant = true,
emptyTitle = "No refactoring plans",
@@ -301,6 +315,8 @@ export function RefactoringBoard({
open={modalOpen}
onOpenChange={setModalOpen}
onAiPrompt={onAiPrompt}
+ onGenerateCode={onGenerateCode}
+ settingsHref={settingsHref}
fileHref={fileHref}
/>
</div>
diff --git a/packages/ui/src/refactoring/refactoring-modal.tsx b/packages/ui/src/refactoring/refactoring-modal.tsx
index 334fee1f5..188ad9e60 100644
--- a/packages/ui/src/refactoring/refactoring-modal.tsx
+++ b/packages/ui/src/refactoring/refactoring-modal.tsx
@@ -1,8 +1,9 @@
"use client";
-import { Layers, Sparkles, TrendingUp } from "lucide-react";
+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,
@@ -11,6 +12,7 @@ import {
planWins,
type Confidence,
type EffortBucket,
+ type GeneratedCode,
type RefactoringPlan,
} from "./types";
@@ -19,6 +21,13 @@ export interface RefactoringModalProps {
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;
}
@@ -40,13 +49,21 @@ export function RefactoringModal({
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} fileHref={fileHref} />
+ <ModalBody
+ plan={plan}
+ onAiPrompt={onAiPrompt}
+ onGenerateCode={onGenerateCode}
+ settingsHref={settingsHref}
+ fileHref={fileHref}
+ />
) : (
<DialogTitle className="sr-only">Refactoring plan</DialogTitle>
)}
@@ -58,10 +75,14 @@ export function RefactoringModal({
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);
@@ -132,6 +153,27 @@ function ModalBody({
<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">
diff --git a/packages/ui/src/refactoring/refactoring-settings-card.tsx b/packages/ui/src/refactoring/refactoring-settings-card.tsx
new file mode 100644
index 000000000..7545efe1b
--- /dev/null
+++ b/packages/ui/src/refactoring/refactoring-settings-card.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import * as React from "react";
+import { Check, Loader2, TriangleAlert, Wand2 } from "lucide-react";
+import { Switch } from "../ui/switch";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+
+export interface RefactoringSettingsValue {
+ enabled: boolean;
+ provider: string | null;
+ model: string | null;
+}
+
+export interface RefactoringSettingsCardProps {
+ /** Current persisted settings, or null while loading. */
+ value: RefactoringSettingsValue | null;
+ /** Persist the new settings. Host owns the API call. */
+ onSave: (value: RefactoringSettingsValue) => Promise<void>;
+ /** True while the initial settings load is in flight. */
+ loading?: boolean;
+ /** Set when settings are unavailable (e.g. no local checkout on this server). */
+ unavailableReason?: string | null;
+}
+
+type SaveState = "idle" | "saving" | "saved" | "error";
+
+/**
+ * The opt-in code-generation switch (`refactoring.llm`). A toggle plus optional
+ * provider/model overrides, written to the repo's config. Presentation only —
+ * the host wires `onSave` to the settings endpoint — so the hosted frontend can
+ * reuse it unchanged.
+ */
+export function RefactoringSettingsCard({
+ value,
+ onSave,
+ loading = false,
+ unavailableReason = null,
+}: RefactoringSettingsCardProps) {
+ const [enabled, setEnabled] = React.useState(false);
+ const [provider, setProvider] = React.useState("");
+ const [model, setModel] = React.useState("");
+ const [save, setSave] = React.useState<SaveState>("idle");
+ const [error, setError] = React.useState<string | null>(null);
+
+ // Seed the form from the persisted value once it arrives / changes.
+ React.useEffect(() => {
+ if (!value) return;
+ setEnabled(value.enabled);
+ setProvider(value.provider ?? "");
+ setModel(value.model ?? "");
+ }, [value]);
+
+ const dirty =
+ value !== null &&
+ (enabled !== value.enabled ||
+ provider !== (value.provider ?? "") ||
+ model !== (value.model ?? ""));
+
+ const persist = React.useCallback(async () => {
+ setSave("saving");
+ setError(null);
+ try {
+ await onSave({
+ enabled,
+ provider: provider.trim() || null,
+ model: model.trim() || null,
+ });
+ setSave("saved");
+ window.setTimeout(() => setSave("idle"), 1800);
+ } catch (err) {
+ setSave("error");
+ setError(err instanceof Error ? err.message : "Could not save settings.");
+ }
+ }, [enabled, provider, model, onSave]);
+
+ if (unavailableReason) {
+ return (
+ <p className="text-sm text-[var(--color-text-tertiary)]">{unavailableReason}</p>
+ );
+ }
+
+ if (loading || value === null) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Loading settings…
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-0.5">
+ <div className="flex items-center gap-2">
+ <Wand2 className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ <Label htmlFor="refactoring-llm-enabled" className="text-sm font-medium">
+ Generate code from plans
+ </Label>
+ </div>
+ <p className="max-w-prose text-xs text-[var(--color-text-tertiary)]">
+ Let the Refactoring tab turn a deterministic plan into a reviewable diff using your
+ configured model. Off by default; never runs during indexing. Suggestion only — no
+ auto-apply.
+ </p>
+ </div>
+ <Switch
+ id="refactoring-llm-enabled"
+ checked={enabled}
+ onCheckedChange={(next) => setEnabled(Boolean(next))}
+ />
+ </div>
+
+ {enabled ? (
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="space-y-1.5">
+ <Label htmlFor="refactoring-llm-provider" className="text-xs text-[var(--color-text-secondary)]">
+ Provider <span className="text-[var(--color-text-tertiary)]">(optional)</span>
+ </Label>
+ <Input
+ id="refactoring-llm-provider"
+ value={provider}
+ onChange={(e) => setProvider(e.target.value)}
+ placeholder="repo default (e.g. anthropic)"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="refactoring-llm-model" className="text-xs text-[var(--color-text-secondary)]">
+ Model <span className="text-[var(--color-text-tertiary)]">(optional)</span>
+ </Label>
+ <Input
+ id="refactoring-llm-model"
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ placeholder="repo default"
+ />
+ </div>
+ </div>
+ ) : null}
+
+ {error ? (
+ <div className="flex items-start gap-2 text-xs text-[var(--color-error)]">
+ <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {error}
+ </div>
+ ) : null}
+
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ onClick={persist}
+ disabled={!dirty || save === "saving"}
+ className="inline-flex items-center gap-1.5 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 disabled:opacity-50"
+ >
+ {save === "saving" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
+ Save
+ </button>
+ {save === "saved" ? (
+ <span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-success)]">
+ <Check className="h-3.5 w-3.5" />
+ Saved
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index e3fe56a10..715148498 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -215,6 +215,84 @@ export interface PlanWin {
label: string;
}
+// ── Generated code (the opt-in LLM enrichment result) ─────────────────────
+
+export interface GeneratedSpan {
+ file: string;
+ line_start: number;
+ line_end: number;
+}
+
+/**
+ * The result of the "Generate code" action — mirrors the backend
+ * `GenerateCodeResponse` (POST `…/refactoring/{id}/generate-code`). `diff` is a
+ * unified diff; `validation` is the per-type self-check (open dict, read
+ * defensively via {@link generatedVerdict}).
+ */
+export interface GeneratedCode {
+ suggestion_id: string | null;
+ refactoring_type: string;
+ file_path: string;
+ target_symbol: string;
+ content: string;
+ diff: string;
+ provider: string;
+ model: string;
+ cached: boolean;
+ input_tokens: number;
+ output_tokens: number;
+ validation: Record<string, unknown>;
+ spans: GeneratedSpan[];
+}
+
+export type VerdictTone = "pass" | "fail" | "neutral";
+
+export interface GeneratedVerdict {
+ tone: VerdictTone;
+ /** Short headline, e.g. "Cohesion improved" / "Self-check skipped". */
+ label: string;
+ /** Optional supporting detail (the metric deltas, or the skip reason). */
+ detail?: string;
+}
+
+function fmtMetric(value: unknown): string | null {
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
+}
+
+/**
+ * Read the Extract Class self-check (LCOM4 + TCC before/after) into a single
+ * verdict for the UI. Other types — and any skipped/absent check — return a
+ * neutral note rather than a false pass.
+ */
+export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null {
+ const v = result.validation;
+ if (!v || typeof v !== "object") return null;
+ const status = v.status;
+ if (status === "skipped") {
+ const reason = typeof v.reason === "string" ? v.reason : null;
+ return { tone: "neutral", label: "Self-check skipped", ...(reason ? { detail: reason } : {}) };
+ }
+ if (status !== "checked") return null;
+
+ const improved = v.improved === true;
+ const parts: string[] = [];
+ const beforeL = fmtMetric(v.before_lcom4);
+ const afterL = fmtMetric(v.after_max_lcom4);
+ if (beforeL !== null && afterL !== null) parts.push(`LCOM4 ${beforeL} → ${afterL}`);
+ const beforeT = fmtMetric(v.before_tcc);
+ const afterT = fmtMetric(v.after_min_tcc);
+ if (beforeT !== null && afterT !== null) parts.push(`TCC ${beforeT} → ${afterT}`);
+ const classes = fmtMetric(v.class_count);
+ if (classes !== null) parts.push(`${classes} classes`);
+
+ return {
+ tone: improved ? "pass" : "fail",
+ label: improved ? "Cohesion improved" : "Cohesion not improved",
+ ...(parts.length ? { detail: parts.join(" · ") } : {}),
+ };
+}
+
/** The concrete payoff of applying a plan, framed as wins for the "what you
* gain" band. The health delta (if any) leads as the hero. */
export function planWins(plan: RefactoringPlan): PlanWin[] {
diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsx
index 2d9378d76..8aa01f3e1 100644
--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx
+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx
@@ -19,7 +19,12 @@ import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { RefactoringBoard, TYPE_ORDER, typeMeta } from "@repowise-dev/ui/refactoring";
import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
import { AiPromptModal, buildRefactoringPlanPrompt } from "@repowise-dev/ui/health";
-import { getRefactoringTargets } from "@/lib/api/refactoring";
+import {
+ generateRefactoringCode,
+ getRefactoringSettings,
+ getRefactoringTargets,
+ type RefactoringSettings,
+} from "@/lib/api/refactoring";
const TYPE_VALUES = ["all", ...TYPE_ORDER] as const;
type TypeFilter = (typeof TYPE_VALUES)[number];
@@ -49,6 +54,22 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
const [promptPlan, setPromptPlan] = useState<RefactoringPlan | null>(null);
const onAiPrompt = useCallback((plan: RefactoringPlan) => setPromptPlan(plan), []);
+ // Opt-in code generation. Enabled only when the repo's config turns it on
+ // (a local-`serve` capability); the settings call 404s on hosted backends,
+ // which simply leaves the action hidden.
+ const { data: settings } = useSWR<RefactoringSettings>(
+ `refactoring-settings:${repoId}`,
+ () => getRefactoringSettings(repoId),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+ const onGenerateCode = useMemo(
+ () =>
+ settings?.enabled
+ ? (plan: RefactoringPlan) => generateRefactoringCode(repoId, plan.id)
+ : undefined,
+ [settings?.enabled, repoId],
+ );
+
const counts = new Map((data?.summary.by_type ?? []).map((c) => [c.type, c.count]));
const tabs = [
{ id: "all" as const, label: "All", badge: data?.summary.total },
@@ -101,6 +122,8 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri
plans={filtered}
summary={data?.summary}
onAiPrompt={onAiPrompt}
+ onGenerateCode={onGenerateCode}
+ settingsHref={`${prefix}/settings`}
fileHref={fileHref}
/>
)}
diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsx
index 16f6c0dd7..69975b142 100644
--- a/packages/web/src/app/repos/[id]/settings/page.tsx
+++ b/packages/web/src/app/repos/[id]/settings/page.tsx
@@ -3,6 +3,7 @@ import Link from "next/link";
import { notFound } from "next/navigation";
import { Settings } from "lucide-react";
import { WebhookSection } from "@/components/settings/webhook-section";
+import { RefactoringSettingsSection } from "@/components/repos/refactoring-settings-section";
import { getRepo } from "@/lib/api/repos";
import { getCoordinatorHealth } from "@/lib/api/health";
import { RepoSettingsFormWrapper as RepoSettingsForm } from "@/components/repos/repo-settings-form-wrapper";
@@ -66,6 +67,18 @@ export default async function RepoSettingsPage({ params }: Props) {
</CardContent>
</Card>
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-sm font-medium">Refactoring code generation</CardTitle>
+ <CardDescription>
+ Opt in to turning refactoring plans into reviewable diffs with your configured model
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <RefactoringSettingsSection repoId={id} />
+ </CardContent>
+ </Card>
+
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">System Health</CardTitle>
diff --git a/packages/web/src/components/repos/refactoring-settings-section.tsx b/packages/web/src/components/repos/refactoring-settings-section.tsx
new file mode 100644
index 000000000..7ec5ada79
--- /dev/null
+++ b/packages/web/src/components/repos/refactoring-settings-section.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import useSWR from "swr";
+import {
+ RefactoringSettingsCard,
+ type RefactoringSettingsValue,
+} from "@repowise-dev/ui/refactoring";
+import {
+ getRefactoringSettings,
+ updateRefactoringSettings,
+ type RefactoringSettings,
+} from "@/lib/api/refactoring";
+import { ApiClientError } from "@/lib/api/client";
+
+/**
+ * Repo settings → code-generation toggle. Reads/writes the `refactoring.llm`
+ * block in the repo's config. The endpoint is a local-`serve` capability, so a
+ * 404 (no accessible checkout, e.g. hosted) renders a quiet unavailable note
+ * rather than an error.
+ */
+export function RefactoringSettingsSection({ repoId }: { repoId: string }) {
+ const { data, error, isLoading, mutate } = useSWR<RefactoringSettings>(
+ `refactoring-settings:${repoId}`,
+ () => getRefactoringSettings(repoId),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
+ const unavailable =
+ error instanceof ApiClientError && error.status === 404
+ ? "Code generation is only available when the repository is served from a local checkout."
+ : error
+ ? "Could not load code-generation settings."
+ : null;
+
+ const onSave = async (value: RefactoringSettingsValue) => {
+ const saved = await updateRefactoringSettings(repoId, value);
+ await mutate(saved, { revalidate: false });
+ };
+
+ return (
+ <RefactoringSettingsCard
+ value={data ?? null}
+ onSave={onSave}
+ loading={isLoading}
+ unavailableReason={unavailable}
+ />
+ );
+}
diff --git a/packages/web/src/lib/api/client.ts b/packages/web/src/lib/api/client.ts
index 0ff542acc..d6a3d9b88 100644
--- a/packages/web/src/lib/api/client.ts
+++ b/packages/web/src/lib/api/client.ts
@@ -106,6 +106,21 @@ export async function apiPost<T>(
return handleResponse<T>(res);
}
+export async function apiPut<T>(
+ path: string,
+ body?: unknown,
+ fetchOptions?: RequestInit,
+): Promise<T> {
+ const url = `${BASE_URL}${path}`;
+ const res = await fetch(url, {
+ method: "PUT",
+ headers: buildHeaders(),
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ ...fetchOptions,
+ });
+ return handleResponse<T>(res);
+}
+
export async function apiPatch<T>(
path: string,
body?: unknown,
diff --git a/packages/web/src/lib/api/refactoring.ts b/packages/web/src/lib/api/refactoring.ts
index f96f493a8..d24db8317 100644
--- a/packages/web/src/lib/api/refactoring.ts
+++ b/packages/web/src/lib/api/refactoring.ts
@@ -3,8 +3,19 @@
* Backend: packages/server/src/repowise/server/routers/refactoring.py
*/
-import { apiGet } from "./client";
-import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+import { apiGet, apiPost, apiPut } from "./client";
+import type { GeneratedCode, RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";
+
+export interface RefactoringSettings {
+ enabled: boolean;
+ provider: string | null;
+ model: string | null;
+}
+
+export interface GenerateCodeOverrides {
+ provider?: string;
+ model?: string;
+}
export interface RefactoringTargetsParams {
refactoringType?: string;
@@ -27,3 +38,26 @@ export async function getRefactoringPlan(
): Promise<RefactoringPlan> {
return apiGet<RefactoringPlan>(`/api/repos/${repoId}/refactoring/${suggestionId}`);
}
+
+/** Opt-in: generate the refactored code + a diff for one plan (Phase-5 endpoint). */
+export async function generateRefactoringCode(
+ repoId: string,
+ suggestionId: string,
+ overrides: GenerateCodeOverrides = {},
+): Promise<GeneratedCode> {
+ return apiPost<GeneratedCode>(
+ `/api/repos/${repoId}/refactoring/${suggestionId}/generate-code`,
+ overrides,
+ );
+}
+
+export async function getRefactoringSettings(repoId: string): Promise<RefactoringSettings> {
+ return apiGet<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`);
+}
+
+export async function updateRefactoringSettings(
+ repoId: string,
+ settings: RefactoringSettings,
+): Promise<RefactoringSettings> {
+ return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, settings);
+}
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index e2918ef54..3dafaa2ce 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -50,6 +50,33 @@ def _require_language(language: str) -> None:
pytest.skip(f"tree-sitter language pack missing for {language}")
+def test_tcc_cohesive_vs_split():
+ """TCC is 1.0 when every method pair shares a field, lower when the class
+ splinters into disjoint field groups."""
+ _require_language("python")
+
+ cohesive = (
+ b"class C:\n"
+ b" def a(self):\n self.x = 1\n"
+ b" def b(self):\n return self.x\n"
+ b" def c(self):\n self.x += 1\n"
+ )
+ split = (
+ b"class D:\n"
+ b" def a(self):\n self.x = 1\n"
+ b" def b(self):\n return self.x\n"
+ b" def c(self):\n self.y = 1\n"
+ b" def d(self):\n return self.y\n"
+ )
+ c = next(k for k in walk_file("c.py", "python", cohesive).classes if k.name == "C")
+ d = next(k for k in walk_file("d.py", "python", split).classes if k.name == "D")
+
+ assert c.tcc == 1.0
+ # D has 6 method pairs, 2 connected (a-b via x, c-d via y) -> 1/3.
+ assert d.tcc == pytest.approx(2 / 6)
+ assert d.tcc < c.tcc
+
+
def test_python_nested_depth():
results = _walk("python/nested.py", "python")
deep = _find(results, "deeply_nested")
diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.py
index e37071517..530f757c1 100644
--- a/tests/unit/health/test_refactoring_enrich.py
+++ b/tests/unit/health/test_refactoring_enrich.py
@@ -243,6 +243,8 @@ async def test_self_check_skipped_for_non_extract_class(tmp_path: Path) -> None:
def test_llm_enrichment_enabled_gate() -> None:
assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": True}}}) is True
+ # Only an explicit false disables it; an unset key defaults on (the local
+ # serve experience works without a config trip).
assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": False}}}) is False
- assert llm_enrichment_enabled({"refactoring": {}}) is False
- assert llm_enrichment_enabled({}) is False
+ assert llm_enrichment_enabled({"refactoring": {}}) is True
+ assert llm_enrichment_enabled({}) is True
diff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.py
index 263cb596c..91db891b8 100644
--- a/tests/unit/server/mcp/test_refactoring.py
+++ b/tests/unit/server/mcp/test_refactoring.py
@@ -22,9 +22,9 @@ async def _setup(factory, *, enabled: bool) -> tuple[Path, str]:
repo_dir = Path(tempfile.mkdtemp()) / "mcp-enrich"
(repo_dir / "pkg").mkdir(parents=True, exist_ok=True)
(repo_dir / ".repowise").mkdir(exist_ok=True)
+ # enabled defaults on, so the disabled case writes an explicit false.
cfg = "provider: mock\n"
- if enabled:
- cfg += "refactoring:\n llm:\n enabled: true\n"
+ cfg += f"refactoring:\n llm:\n enabled: {'true' if enabled else 'false'}\n"
(repo_dir / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
(repo_dir / "pkg" / "leaf.py").write_text(
"class GodClass:\n def a(self):\n return 1\n", encoding="utf-8"
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 478eabfb0..05a239b16 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -37,85 +37,148 @@ async def _seed(client: AsyncClient, app) -> str:
repo_id = repo["id"]
async with app.state.session_factory() as session:
- await batch_upsert_graph_nodes(session, repo_id, [
- {"node_id": "pkg/hub.py", "node_type": "file", "language": "python", "symbol_count": 9},
- {"node_id": "pkg/leaf.py", "node_type": "file", "language": "python", "symbol_count": 3},
- {"node_id": "pkg/a.py", "node_type": "file", "language": "python", "symbol_count": 2},
- {"node_id": "pkg/b.py", "node_type": "file", "language": "python", "symbol_count": 2},
- ])
+ await batch_upsert_graph_nodes(
+ session,
+ repo_id,
+ [
+ {
+ "node_id": "pkg/hub.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 9,
+ },
+ {
+ "node_id": "pkg/leaf.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 3,
+ },
+ {
+ "node_id": "pkg/a.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 2,
+ },
+ {
+ "node_id": "pkg/b.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 2,
+ },
+ ],
+ )
# hub.py has in-degree 2 (a, b import it); leaf.py has in-degree 0.
- await batch_upsert_graph_edges(session, repo_id, [
- {"source_node_id": "pkg/a.py", "target_node_id": "pkg/hub.py", "edge_type": "imports"},
- {"source_node_id": "pkg/b.py", "target_node_id": "pkg/hub.py", "edge_type": "imports"},
- ])
- await crud.save_refactoring_suggestions(session, repo_id, [
- {
- "refactoring_type": "extract_class",
- "file_path": "pkg/leaf.py",
- "target_symbol": "GodClass",
- "line_start": 1,
- "line_end": 200,
- "plan": {"groups": [
- {"name": None, "methods": ["a", "b"], "fields": ["x"]},
- {"name": None, "methods": ["c", "d"], "fields": ["y"]},
- ]},
- "evidence": {"lcom4": 2, "method_count": 6, "field_count": 2, "wmc": 40},
- "impact_delta": 2.5,
- "effort_bucket": "L",
- "blast_radius": {"dependents_count": 0},
- "confidence": "high",
- "source_biomarker": "low_cohesion",
- },
- {
- "refactoring_type": "extract_helper",
- "file_path": "pkg/hub.py",
- "target_symbol": "dup_block",
- "line_start": 10,
- "line_end": 30,
- "plan": {
- "occurrences": [
- {"file": "pkg/hub.py", "line_start": 10, "line_end": 30},
- {"file": "pkg/a.py", "line_start": 5, "line_end": 25},
- ],
- "suggested_site": {"module": "pkg", "directory": "pkg"},
- "duplicated_lines": 20,
+ await batch_upsert_graph_edges(
+ session,
+ repo_id,
+ [
+ {
+ "source_node_id": "pkg/a.py",
+ "target_node_id": "pkg/hub.py",
+ "edge_type": "imports",
},
- "evidence": {"occurrence_count": 2, "duplicated_lines": 20, "co_change_count": 4},
- "impact_delta": 0.6,
- "effort_bucket": "M",
- "blast_radius": {"files": ["pkg/hub.py", "pkg/a.py"], "file_count": 2, "co_change_count": 4},
- "confidence": "high",
- "source_biomarker": "dry_violation",
- },
- {
- "refactoring_type": "move_method",
- "file_path": "pkg/a.py",
- "target_symbol": "Helper.do_work",
- "line_start": 40,
- "line_end": 60,
- "plan": {"method": "do_work", "from_class": "Helper", "to_class": "Worker", "to_file": "pkg/b.py"},
- "evidence": {"foreign_calls": 3, "own_calls": 0, "own_distance": 0.95, "target_distance": 0.4},
- "impact_delta": 0.0,
- "effort_bucket": "S",
- "blast_radius": {"callers": 1, "files": ["pkg/a.py", "pkg/b.py"]},
- "confidence": "medium",
- "source_biomarker": "",
- },
- {
- "refactoring_type": "break_cycle",
- "file_path": "pkg/a.py",
- "target_symbol": "pkg/a.py↔pkg/b.py",
- "line_start": None,
- "line_end": None,
- "plan": {"cycle": ["pkg/a.py", "pkg/b.py"], "cut_edges": [{"from": "pkg/a.py", "to": "pkg/b.py"}]},
- "evidence": {"cycle_size": 2, "edge_count": 2, "cut_count": 1},
- "impact_delta": 0.0,
- "effort_bucket": "M",
- "blast_radius": {"files": ["pkg/a.py", "pkg/b.py"], "file_count": 2},
- "confidence": "medium",
- "source_biomarker": "",
- },
- ])
+ {
+ "source_node_id": "pkg/b.py",
+ "target_node_id": "pkg/hub.py",
+ "edge_type": "imports",
+ },
+ ],
+ )
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ {
+ "refactoring_type": "extract_class",
+ "file_path": "pkg/leaf.py",
+ "target_symbol": "GodClass",
+ "line_start": 1,
+ "line_end": 200,
+ "plan": {
+ "groups": [
+ {"name": None, "methods": ["a", "b"], "fields": ["x"]},
+ {"name": None, "methods": ["c", "d"], "fields": ["y"]},
+ ]
+ },
+ "evidence": {"lcom4": 2, "method_count": 6, "field_count": 2, "wmc": 40},
+ "impact_delta": 2.5,
+ "effort_bucket": "L",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "high",
+ "source_biomarker": "low_cohesion",
+ },
+ {
+ "refactoring_type": "extract_helper",
+ "file_path": "pkg/hub.py",
+ "target_symbol": "dup_block",
+ "line_start": 10,
+ "line_end": 30,
+ "plan": {
+ "occurrences": [
+ {"file": "pkg/hub.py", "line_start": 10, "line_end": 30},
+ {"file": "pkg/a.py", "line_start": 5, "line_end": 25},
+ ],
+ "suggested_site": {"module": "pkg", "directory": "pkg"},
+ "duplicated_lines": 20,
+ },
+ "evidence": {
+ "occurrence_count": 2,
+ "duplicated_lines": 20,
+ "co_change_count": 4,
+ },
+ "impact_delta": 0.6,
+ "effort_bucket": "M",
+ "blast_radius": {
+ "files": ["pkg/hub.py", "pkg/a.py"],
+ "file_count": 2,
+ "co_change_count": 4,
+ },
+ "confidence": "high",
+ "source_biomarker": "dry_violation",
+ },
+ {
+ "refactoring_type": "move_method",
+ "file_path": "pkg/a.py",
+ "target_symbol": "Helper.do_work",
+ "line_start": 40,
+ "line_end": 60,
+ "plan": {
+ "method": "do_work",
+ "from_class": "Helper",
+ "to_class": "Worker",
+ "to_file": "pkg/b.py",
+ },
+ "evidence": {
+ "foreign_calls": 3,
+ "own_calls": 0,
+ "own_distance": 0.95,
+ "target_distance": 0.4,
+ },
+ "impact_delta": 0.0,
+ "effort_bucket": "S",
+ "blast_radius": {"callers": 1, "files": ["pkg/a.py", "pkg/b.py"]},
+ "confidence": "medium",
+ "source_biomarker": "",
+ },
+ {
+ "refactoring_type": "break_cycle",
+ "file_path": "pkg/a.py",
+ "target_symbol": "pkg/a.py↔pkg/b.py",
+ "line_start": None,
+ "line_end": None,
+ "plan": {
+ "cycle": ["pkg/a.py", "pkg/b.py"],
+ "cut_edges": [{"from": "pkg/a.py", "to": "pkg/b.py"}],
+ },
+ "evidence": {"cycle_size": 2, "edge_count": 2, "cut_count": 1},
+ "impact_delta": 0.0,
+ "effort_bucket": "M",
+ "blast_radius": {"files": ["pkg/a.py", "pkg/b.py"], "file_count": 2},
+ "confidence": "medium",
+ "source_biomarker": "",
+ },
+ ],
+ )
await session.commit()
return repo_id
@@ -184,10 +247,14 @@ async def test_centrality_breaks_ties_in_ranking(client: AsyncClient, app) -> No
repo = await create_test_repo(client)
repo_id = repo["id"]
async with app.state.session_factory() as session:
- await crud.batch_upsert_graph_metrics(session, repo_id, {
- "pkg/hub.py": {"in_degree": 25, "out_degree": 1},
- "pkg/leaf.py": {"in_degree": 0, "out_degree": 1},
- })
+ await crud.batch_upsert_graph_metrics(
+ session,
+ repo_id,
+ {
+ "pkg/hub.py": {"in_degree": 25, "out_degree": 1},
+ "pkg/leaf.py": {"in_degree": 0, "out_degree": 1},
+ },
+ )
# Same type, effort, confidence, impact, blast — only the file differs.
common = {
"refactoring_type": "extract_class",
@@ -202,10 +269,14 @@ async def test_centrality_breaks_ties_in_ranking(client: AsyncClient, app) -> No
"confidence": "medium",
"source_biomarker": "low_cohesion",
}
- await crud.save_refactoring_suggestions(session, repo_id, [
- {**common, "file_path": "pkg/leaf.py"},
- {**common, "file_path": "pkg/hub.py"},
- ])
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ {**common, "file_path": "pkg/leaf.py"},
+ {**common, "file_path": "pkg/hub.py"},
+ ],
+ )
await session.commit()
body = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()
@@ -241,12 +312,13 @@ async def _seed_enrich_repo(client: AsyncClient, app, *, enabled: bool) -> tuple
(repo_dir / "pkg").mkdir(parents=True, exist_ok=True)
(repo_dir / ".git").mkdir(exist_ok=True)
(repo_dir / ".repowise").mkdir(exist_ok=True)
+ # enabled defaults on, so the disabled case writes an explicit false.
cfg = "provider: mock\n"
- if enabled:
- cfg += "refactoring:\n llm:\n enabled: true\n"
+ cfg += f"refactoring:\n llm:\n enabled: {'true' if enabled else 'false'}\n"
(repo_dir / ".repowise" / "config.yaml").write_text(cfg, encoding="utf-8")
(repo_dir / "pkg" / "leaf.py").write_text(
- "class GodClass:\n" + "".join(f" def m{i}(self):\n return {i}\n" for i in range(6)),
+ "class GodClass:\n"
+ + "".join(f" def m{i}(self):\n return {i}\n" for i in range(6)),
encoding="utf-8",
)
@@ -262,22 +334,26 @@ async def _seed_enrich_repo(client: AsyncClient, app, *, enabled: bool) -> tuple
repo_id = resp.json()["id"]
async with app.state.session_factory() as session:
- await crud.save_refactoring_suggestions(session, repo_id, [
- {
- "refactoring_type": "extract_class",
- "file_path": "pkg/leaf.py",
- "target_symbol": "GodClass",
- "line_start": 1,
- "line_end": 12,
- "plan": {"groups": [{"name": None, "methods": ["m0"], "fields": []}]},
- "evidence": {"lcom4": 2, "method_count": 6, "field_count": 0, "wmc": 6},
- "impact_delta": 2.5,
- "effort_bucket": "L",
- "blast_radius": {"dependents_count": 0},
- "confidence": "high",
- "source_biomarker": "low_cohesion",
- },
- ])
+ await crud.save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ {
+ "refactoring_type": "extract_class",
+ "file_path": "pkg/leaf.py",
+ "target_symbol": "GodClass",
+ "line_start": 1,
+ "line_end": 12,
+ "plan": {"groups": [{"name": None, "methods": ["m0"], "fields": []}]},
+ "evidence": {"lcom4": 2, "method_count": 6, "field_count": 0, "wmc": 6},
+ "impact_delta": 2.5,
+ "effort_bucket": "L",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "high",
+ "source_biomarker": "low_cohesion",
+ },
+ ],
+ )
await session.commit()
rows = await crud.get_refactoring_suggestions(session, repo_id)
suggestion_id = rows[0].id
@@ -306,3 +382,67 @@ async def test_generate_code_unknown_id_404(client: AsyncClient, app) -> None:
repo_id, _ = await _seed_enrich_repo(client, app, enabled=True)
resp = await client.post(f"/api/repos/{repo_id}/refactoring/deadbeef/generate-code", json={})
assert resp.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Code-gen settings (refactoring.llm) round-trip
+# ---------------------------------------------------------------------------
+
+
+async def test_settings_default_enabled_when_unset(client: AsyncClient, app) -> None:
+ """An untouched repo (no config) reads as enabled with no provider/model."""
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/refactoring/settings")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body == {"enabled": True, "provider": None, "model": None}
+
+
+async def test_settings_put_round_trips_and_preserves_other_keys(client: AsyncClient, app) -> None:
+ import yaml
+
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ # Seed an unrelated key so we can assert the writer preserves it.
+ repo_dir = Path(repo["local_path"])
+ (repo_dir / ".repowise").mkdir(exist_ok=True)
+ (repo_dir / ".repowise" / "config.yaml").write_text("provider: anthropic\n", encoding="utf-8")
+
+ resp = await client.put(
+ f"/api/repos/{repo_id}/refactoring/settings",
+ json={"enabled": False, "provider": "openai", "model": "gpt-x"},
+ )
+ assert resp.status_code == 200
+ assert resp.json() == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+
+ # GET reflects the write, and the unrelated top-level key survived.
+ got = await client.get(f"/api/repos/{repo_id}/refactoring/settings")
+ assert got.json() == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+ cfg = yaml.safe_load((repo_dir / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+ assert cfg["provider"] == "anthropic"
+ assert cfg["refactoring"]["llm"] == {"enabled": False, "provider": "openai", "model": "gpt-x"}
+
+
+async def test_settings_put_blank_provider_clears_key(client: AsyncClient, app) -> None:
+ import yaml
+
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ await client.put(
+ f"/api/repos/{repo_id}/refactoring/settings",
+ json={"enabled": True, "provider": "openai", "model": "gpt-x"},
+ )
+ # Re-save with blank provider/model -> the keys are removed, not "".
+ resp = await client.put(
+ f"/api/repos/{repo_id}/refactoring/settings",
+ json={"enabled": True, "provider": "", "model": " "},
+ )
+ assert resp.json() == {"enabled": True, "provider": None, "model": None}
+ repo_dir = Path(repo["local_path"])
+ cfg = yaml.safe_load((repo_dir / ".repowise" / "config.yaml").read_text(encoding="utf-8"))
+ assert cfg["refactoring"]["llm"] == {"enabled": True}
+
+
+async def test_settings_unknown_repo_404(client: AsyncClient, app) -> None:
+ resp = await client.get("/api/repos/does-not-exist/refactoring/settings")
+ assert resp.status_code == 404