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): opt-in LLM code generation from deterministic plans (#592)

Raghav Chamadiyac6c5e0357744
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py
index fa5bca7b7..7f6af1751 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py
@@ -78,6 +78,17 @@ from repowise.cli.helpers import (
default=False,
help="Print top refactoring candidates (impact/effort ratio).",
)
+ "--generate-code",
+ "generate_code",
+ default=None,
+ metavar="SELECTOR",
+ help=(
+ "Opt-in: generate refactored code + a diff for one suggestion via the "
+ "configured LLM. SELECTOR is a 1-based rank (e.g. 1) or a target-symbol "
+ "match. Reuses the repo's provider/model; requires an API key."
+ ),
+)
@click.option(
"--module",
"module_filter",
@@ -108,6 +119,7 @@ def health_command(
coverage_paths: tuple[str, ...],
coverage_format: str | None,
refactoring_targets: bool,
+ generate_code: str | None,
module_filter: str | None,
trend_view: bool,
badge_view: bool,
@@ -285,6 +297,15 @@ def health_command(
if module_filter:
findings = [f for f in findings if f.file_path.startswith(module_filter)]
+ if generate_code is not None:
+ suggestions = getattr(report, "refactoring_suggestions", None) or []
+ if file_filter:
+ suggestions = [s for s in suggestions if s.file_path == file_filter]
+ if module_filter:
+ suggestions = [s for s in suggestions if s.file_path.startswith(module_filter)]
+ _generate_refactoring_code(repo_path, suggestions, generate_code, fmt=fmt)
+ return
+
if refactoring_targets:
suggestions = getattr(report, "refactoring_suggestions", None) or []
if file_filter:
@@ -501,6 +522,89 @@ def _suggestion_to_dict(s: object) -> dict:
return dataclasses.asdict(s) if dataclasses.is_dataclass(s) else dict(s)
+def _select_suggestion(suggestions: list, selector: str):
+ """Pick one suggestion by a 1-based rank or a target-symbol match.
+
+ ``suggestions`` is the engine's unified-ranked list, so ``"1"`` is the top
+ candidate. A non-numeric selector matches ``target_symbol`` exactly first,
+ then falls back to a unique case-insensitive substring match.
+ """
+ if selector.isdigit():
+ idx = int(selector) - 1
+ if 0 <= idx < len(suggestions):
+ return suggestions[idx]
+ raise click.ClickException(
+ f"Rank {selector} is out of range (1-{len(suggestions)} available)."
+ )
+ exact = [s for s in suggestions if s.target_symbol == selector]
+ if len(exact) == 1:
+ return exact[0]
+ needle = selector.lower()
+ partial = [s for s in suggestions if needle in s.target_symbol.lower()]
+ if len(partial) == 1:
+ return partial[0]
+ if not partial:
+ raise click.ClickException(f"No refactoring suggestion matches {selector!r}.")
+ names = ", ".join(sorted({s.target_symbol for s in partial})[:8])
+ raise click.ClickException(
+ f"{selector!r} matches multiple suggestions ({names}). Use a 1-based rank instead."
+ )
+
+
+def _generate_refactoring_code(repo_path, suggestions: list, selector: str, *, fmt: str) -> None:
+ """Opt-in LLM code-gen for one suggestion: resolve provider, enrich, render.
+
+ Reuses the repo's configured provider/model (BYO key). The enrichment layer
+ is the only place the refactoring feature touches an LLM; it never runs in
+ the indexing hot path.
+ """
+ from repowise.cli.helpers import resolve_provider
+ from repowise.core.analysis.health.refactoring.llm import enrich_suggestion
+
+ if not suggestions:
+ raise click.ClickException(
+ "No refactoring suggestions for this repo. Run `repowise health "
+ "--refactoring-targets` first to see what's available."
+ )
+
+ suggestion = _select_suggestion(suggestions, selector)
+
+ try:
+ provider = resolve_provider(None, None, Path(repo_path))
+ except Exception as exc: # provider misconfig surfaces as a clean CLI error
+ raise click.ClickException(
+ f"Could not resolve an LLM provider for code generation: {exc}"
+ ) from exc
+
+ console.print(
+ f"[dim]Generating code for[/dim] [cyan]{suggestion.target_symbol}[/cyan] "
+ f"[dim]({suggestion.refactoring_type}) via {getattr(provider, 'model_name', '?')}...[/dim]"
+ )
+ result = run_async(enrich_suggestion(suggestion, provider=provider, repo_path=Path(repo_path)))
+
+ if fmt == "json":
+ click.echo(json.dumps(result.to_dict(), indent=2))
+ return
+
+ cached = " [dim](cached)[/dim]" if result.cached else ""
+ console.print(
+ f"\n[bold]{suggestion.refactoring_type}[/bold] · {suggestion.target_symbol} "
+ f"[dim]({result.model})[/dim]{cached}"
+ )
+ if result.validation.get("status") == "checked":
+ v = result.validation
+ verdict = (
+ "[green]improves cohesion[/green]"
+ if v.get("improved")
+ else "[yellow]no LCOM4 improvement detected[/yellow]"
+ )
+ console.print(
+ f"[dim]Self-check: LCOM4 {v.get('before_lcom4')} → "
+ f"max {v.get('after_max_lcom4')} across {v.get('class_count')} classes — {verdict}[/dim]"
+ )
+ console.print(result.content)
+
+
def _render_refactoring_targets(
metrics: list, findings: list, suggestions: list | None = None, *, fmt: str, limit: int = 20
) -> None:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py
new file mode 100644
index 000000000..1d7cdbd8a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/__init__.py
@@ -0,0 +1,28 @@
+"""Opt-in LLM enrichment of deterministic refactoring plans.
+
+The deterministic layer (``refactoring/``) produces structured
+``RefactoringSuggestion`` plans with zero LLM calls. This subpackage is the
+strictly-optional second step: on demand, it hands one plan plus the real
+source spans it references to an LLM and gets back the named, refactored code
+and a unified diff. It is never imported by the indexing hot path — only by the
+edges (CLI ``--generate-code``, the web ``/generate-code`` endpoint, the MCP
+tool) when a human explicitly asks for code.
+"""
+
+from __future__ import annotations
+
+from .enrich import (
+ EnrichmentResult,
+ SourceSpan,
+ build_enrichment_provider,
+ enrich_suggestion,
+ llm_enrichment_enabled,
+)
+
+__all__ = [
+ "EnrichmentResult",
+ "SourceSpan",
+ "build_enrichment_provider",
+ "enrich_suggestion",
+ "llm_enrichment_enabled",
+]
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
new file mode 100644
index 000000000..e5a6e5222
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -0,0 +1,574 @@
+"""On-demand LLM enrichment: a deterministic plan -> named code + a diff.
+
+This closes the loop from a structured ``RefactoringSuggestion`` (the split
+groups, the clone occurrences, the cycle cut-edges) to the actual refactored
+code a human or coding agent can apply. It is strictly opt-in and never runs in
+the indexing hot path:
+
+1. Gather the real source spans the plan references (the class body, every clone
+ occurrence, the method to move, the files on each cut edge) straight off the
+ working tree.
+2. Build a behaviour-preservation prompt carrying the structured plan + that
+ source + the graph/co-change context the deterministic layer already
+ computed, and ask the configured provider for the refactored code and a
+ unified diff.
+3. For Extract Class, self-check the result with an LCOM4 before/after delta
+ (re-walk the generated classes) so we can say whether the split actually
+ improved cohesion. Other types skip validation gracefully.
+
+Results are cached on disk by a content hash (plan + source + model), so the
+same plan never pays for the same generation twice.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.providers.llm.base import BaseProvider, CacheHint
+
+log = structlog.get_logger(__name__)
+
+# Bounds so a pathological plan can never balloon the prompt: per-span and
+# total source-line caps, and a hard ceiling on how many spans we read.
+_MAX_SPAN_LINES = 240
+_MAX_SPANS = 12
+# Cache lives next to the other repo-local refactoring artifacts.
+_CACHE_SUBDIR = ("refactoring", "enrich")
+
+# Extension -> tree-sitter language name (the names ``walk_file`` understands).
+# Only the languages whose LCOM4 self-check is meaningful need to be here; an
+# unknown extension simply skips validation.
+_EXT_LANGUAGE: dict[str, str] = {
+ ".py": "python",
+ ".ts": "typescript",
+ ".tsx": "typescript",
+ ".js": "javascript",
+ ".jsx": "javascript",
+ ".java": "java",
+ ".go": "go",
+ ".cs": "c_sharp",
+ ".rb": "ruby",
+ ".php": "php",
+ ".kt": "kotlin",
+ ".rs": "rust",
+ ".scala": "scala",
+ ".swift": "swift",
+}
+
+
+@dataclass
+class SourceSpan:
+ """A concrete slice of working-tree source the plan refers to."""
+
+ file: str
+ start_line: int
+ end_line: int
+ source: str
+
+
+@dataclass
+class EnrichmentResult:
+ """The output of enriching one suggestion. Serialized to every surface."""
+
+ refactoring_type: str
+ file_path: str
+ target_symbol: str
+ suggestion_id: str | None
+ # The model's full response (a short summary + the named code + the diff).
+ content: str
+ # The unified diff extracted from the response, when it emitted one.
+ diff: str
+ provider: str
+ model: str
+ cached: bool
+ input_tokens: int
+ output_tokens: int
+ # LCOM4 before/after self-check (Extract Class only); ``{}`` when skipped.
+ validation: dict[str, Any] = field(default_factory=dict)
+ # The spans fed to the model, so a surface can show what was grounded on.
+ spans: list[dict[str, Any]] = field(default_factory=list)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+# ---------------------------------------------------------------------------
+# Config gate + provider resolution (server / MCP surfaces)
+# ---------------------------------------------------------------------------
+
+
+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.
+ """
+ refactoring = config.get("refactoring")
+ if not isinstance(refactoring, dict):
+ return False
+ llm = refactoring.get("llm")
+ if not isinstance(llm, dict):
+ return False
+ return bool(llm.get("enabled", False))
+
+
+def build_enrichment_provider(
+ repo_path: Path,
+ *,
+ provider_name: str | None = None,
+ model: str | None = None,
+) -> BaseProvider:
+ """Resolve a provider for server/MCP enrichment from repo config + env.
+
+ Mirrors the CLI resolver in spirit (config provider/model, key from env)
+ but lives in core so the server and MCP layers don't depend on the CLI.
+ Reads ``.repowise/config.yaml`` for provider/model and the per-repo
+ ``.repowise/.env`` (without mutating ``os.environ``) plus the process env
+ for the API key. Raises ``ValueError`` when no provider/key can be found.
+ """
+ import os
+
+ from repowise.core.providers import get_provider
+ from repowise.core.repo_config import load_repo_config, load_repo_env
+
+ cfg = load_repo_config(repo_path)
+ repo_env = load_repo_env(repo_path)
+
+ def _env(name: str) -> str | None:
+ return os.environ.get(name) or repo_env.get(name)
+
+ name = provider_name or cfg.get("provider")
+ chosen_model = model or cfg.get("model")
+
+ # Map provider -> the env var carrying its key.
+ key_vars = {
+ "anthropic": "ANTHROPIC_API_KEY",
+ "openai": "OPENAI_API_KEY",
+ "openrouter": "OPENROUTER_API_KEY",
+ "deepseek": "DEEPSEEK_API_KEY",
+ "gemini": "GEMINI_API_KEY",
+ "litellm": "LITELLM_API_KEY",
+ }
+
+ # Auto-detect from whichever key is present when the config names none.
+ if name is None:
+ for candidate, var in key_vars.items():
+ if _env(var):
+ name = candidate
+ break
+ if name is None:
+ raise ValueError(
+ "No LLM provider configured for refactoring enrichment. Set "
+ "'provider' in .repowise/config.yaml or an API key env var."
+ )
+
+ kwargs: dict[str, Any] = {}
+ if chosen_model:
+ kwargs["model"] = chosen_model
+ key_var = key_vars.get(name)
+ if key_var and _env(key_var):
+ kwargs["api_key"] = _env(key_var)
+ if name == "gemini" and not kwargs.get("api_key") and _env("GOOGLE_API_KEY"):
+ kwargs["api_key"] = _env("GOOGLE_API_KEY")
+
+ return get_provider(name, **kwargs)
+
+
+# ---------------------------------------------------------------------------
+# Source gathering
+# ---------------------------------------------------------------------------
+
+
+def _read_span(repo_path: Path, file: str, start: int, end: int) -> SourceSpan | None:
+ """Read a 1-indexed inclusive line range off the working tree, capped.
+
+ Guards against reading outside the repo root and degrades to ``None`` on
+ any read error (the caller simply omits the span).
+ """
+ abs_path = (repo_path / file).resolve()
+ try:
+ abs_path.relative_to(repo_path.resolve())
+ except ValueError:
+ log.warning("enrich_span_path_escape", file=file)
+ return None
+ try:
+ text = abs_path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return None
+
+ lines = text.splitlines()
+ total = len(lines)
+ if total == 0:
+ return None
+ s = max(1, min(start, total))
+ e = max(s, min(end, total))
+ if (e - s + 1) > _MAX_SPAN_LINES:
+ e = s + _MAX_SPAN_LINES - 1
+ return SourceSpan(file=file, start_line=s, end_line=e, source="\n".join(lines[s - 1 : e]))
+
+
+def _span_requests(suggestion: Any) -> list[tuple[str, int, int]]:
+ """Per-type (file, start, end) requests, derived from the plan.
+
+ The target span (``file_path`` + ``line_start``/``line_end``) is the spine;
+ each type adds the extra spans its plan references (clone occurrences, the
+ move source/target files, the files on each cut edge). Bounded to
+ ``_MAX_SPANS``; missing line info falls back to the file head.
+ """
+ plan = suggestion.plan or {}
+ rtype = suggestion.refactoring_type
+ requests: list[tuple[str, int, int]] = []
+
+ def _add(file: str | None, start: Any, end: Any) -> None:
+ if not file or len(requests) >= _MAX_SPANS:
+ return
+ try:
+ s = int(start) if start is not None else 1
+ e = int(end) if end is not None else s + _MAX_SPAN_LINES - 1
+ except (TypeError, ValueError):
+ s, e = 1, _MAX_SPAN_LINES
+ requests.append((file, s, e))
+
+ # The headline target span (the class / method / site).
+ if suggestion.file_path:
+ _add(suggestion.file_path, suggestion.line_start, suggestion.line_end)
+
+ if rtype == "extract_helper":
+ for occ in plan.get("occurrences", []) or []:
+ if isinstance(occ, dict):
+ _add(occ.get("file"), occ.get("line_start"), occ.get("line_end"))
+ elif rtype == "move_method":
+ to_file = plan.get("to_file")
+ # The destination class file gives the model the landing context; read
+ # its head (we don't have an exact span for it).
+ _add(to_file, 1, _MAX_SPAN_LINES)
+ elif rtype == "break_cycle":
+ for edge in plan.get("cut_edges", []) or []:
+ if isinstance(edge, dict):
+ # The "from" file holds the import to invert/abstract.
+ _add(edge.get("from"), 1, _MAX_SPAN_LINES)
+
+ # De-dup identical (file, start, end) requests while preserving order.
+ seen: set[tuple[str, int, int]] = set()
+ unique: list[tuple[str, int, int]] = []
+ for req in requests:
+ if req not in seen:
+ seen.add(req)
+ unique.append(req)
+ return unique
+
+
+def _gather_spans(suggestion: Any, repo_path: Path) -> list[SourceSpan]:
+ spans: list[SourceSpan] = []
+ for file, start, end in _span_requests(suggestion):
+ span = _read_span(repo_path, file, start, end)
+ if span is not None:
+ spans.append(span)
+ return spans
+
+
+# ---------------------------------------------------------------------------
+# Prompt assembly
+# ---------------------------------------------------------------------------
+
+_SYSTEM_PROMPT = """\
+You are a senior software engineer performing a single, well-scoped refactoring.
+
+You are given a STRUCTURED PLAN produced by deterministic static analysis and \
+the exact SOURCE SPANS the plan refers to. Carry out exactly that plan and \
+nothing more.
+
+Hard rules:
+- Preserve behaviour exactly. No functional changes, no API changes beyond what \
+the plan requires, no opportunistic cleanup.
+- Use the real names from the source. Invent clear names only for new things the \
+plan leaves unnamed (e.g. extracted classes/helpers).
+- Do not hallucinate code you were not shown. If a needed detail is missing, \
+state the assumption briefly rather than guessing silently.
+
+Respond in this order:
+1. A 1-2 sentence summary of the change.
+2. The new or changed code, each block in a fenced code block tagged with the \
+language.
+3. A single unified diff in one ```diff fenced block (git-style: `--- a/path`, \
+`+++ b/path`, `@@` hunks) covering every file you changed.
+"""
+
+_TYPE_INSTRUCTIONS: dict[str, str] = {
+ "extract_class": (
+ "Refactoring: EXTRACT CLASS. Split the class into the cohesive groups in "
+ "the plan — each group becomes a new class owning its listed methods and "
+ "fields. Keep the original class as a thin coordinator that delegates, so "
+ "all existing call sites keep working."
+ ),
+ "extract_helper": (
+ "Refactoring: EXTRACT HELPER. The occurrences are duplicates of the same "
+ "logic. Extract one shared helper (place it at the suggested site) and "
+ "replace every occurrence with a call to it."
+ ),
+ "move_method": (
+ "Refactoring: MOVE METHOD. Move the method from its current class to the "
+ "target class it is more cohesive with, and update the call sites. Leave a "
+ "thin delegating wrapper only if removing the method outright would break "
+ "callers you cannot see."
+ ),
+ "break_cycle": (
+ "Refactoring: BREAK IMPORT CYCLE. Remove the cyclic dependency by "
+ "inverting or abstracting the import on each cut edge (dependency "
+ "inversion, a shared interface/protocol module, or a local import as a "
+ "last resort). Do not merge the files."
+ ),
+}
+
+
+def _build_user_prompt(suggestion: Any, spans: list[SourceSpan]) -> str:
+ """Render the plan + evidence + blast radius + source into a user prompt."""
+ rtype = suggestion.refactoring_type
+ parts: list[str] = []
+ parts.append(_TYPE_INSTRUCTIONS.get(rtype, f"Refactoring: {rtype}."))
+ parts.append(f"\nTarget: {suggestion.target_symbol} ({suggestion.file_path})")
+
+ parts.append("\n## Structured plan\n")
+ parts.append("```json")
+ parts.append(
+ json.dumps(
+ {
+ "type": rtype,
+ "plan": suggestion.plan or {},
+ "evidence": suggestion.evidence or {},
+ "blast_radius": suggestion.blast_radius or {},
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ parts.append("```")
+
+ parts.append("\n## Source spans\n")
+ if not spans:
+ parts.append("_(no source spans were resolvable from the working tree)_")
+ for span in spans:
+ parts.append(f"### {span.file}:{span.start_line}-{span.end_line}")
+ parts.append("```")
+ parts.append(span.source)
+ parts.append("```")
+
+ return "\n".join(parts)
+
+
+# ---------------------------------------------------------------------------
+# Response parsing + caching
+# ---------------------------------------------------------------------------
+
+_DIFF_FENCE = re.compile(r"```diff\s*\n(.*?)```", re.DOTALL)
+_CODE_FENCE = re.compile(r"```([A-Za-z0-9_+-]*)\s*\n(.*?)```", re.DOTALL)
+
+
+def _extract_diff(content: str) -> str:
+ """Return the first ```diff fenced block, stripped, or ``""``."""
+ match = _DIFF_FENCE.search(content)
+ return match.group(1).strip() if match else ""
+
+
+def _extract_code_blocks(content: str, language: str | None) -> str:
+ """Concatenate non-diff fenced code blocks (best-effort) for the self-check.
+
+ Prefers blocks tagged with the target language but accepts untagged blocks;
+ always skips ``diff`` blocks (those are not parseable source).
+ """
+ wanted = {language} if language else set()
+ # Accept common aliases so a "py"-tagged block still counts as python, etc.
+ aliases = {"py": "python", "ts": "typescript", "tsx": "typescript"}
+ blocks: list[str] = []
+ for tag, body in _CODE_FENCE.findall(content):
+ norm = aliases.get(tag.lower(), tag.lower())
+ if norm == "diff":
+ continue
+ if wanted and norm and norm not in wanted:
+ continue
+ blocks.append(body.strip())
+ return "\n\n".join(blocks)
+
+
+def _language_for(file_path: str) -> str | None:
+ return _EXT_LANGUAGE.get(Path(file_path).suffix.lower())
+
+
+def _cache_key(suggestion: Any, spans: list[SourceSpan], model: str) -> str:
+ payload = json.dumps(
+ {
+ "type": suggestion.refactoring_type,
+ "target": suggestion.target_symbol,
+ "file": suggestion.file_path,
+ "plan": suggestion.plan or {},
+ "spans": [
+ [s.file, s.start_line, s.end_line, hashlib.sha256(s.source.encode()).hexdigest()]
+ for s in spans
+ ],
+ "model": model,
+ },
+ sort_keys=True,
+ )
+ return hashlib.sha256(payload.encode()).hexdigest()
+
+
+def _cache_dir(repo_path: Path) -> Path:
+ return repo_path.joinpath(".repowise", *_CACHE_SUBDIR)
+
+
+def _read_cache(cache_dir: Path, key: str) -> EnrichmentResult | None:
+ path = cache_dir / f"{key}.json"
+ if not path.exists():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ try:
+ result = EnrichmentResult(**data)
+ except TypeError:
+ return None
+ result.cached = True
+ return result
+
+
+def _write_cache(cache_dir: Path, key: str, result: EnrichmentResult) -> None:
+ try:
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ # Persist with cached=False; the read path flips it to True on a hit.
+ payload = result.to_dict()
+ payload["cached"] = False
+ (cache_dir / f"{key}.json").write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ except OSError as exc:
+ log.debug("enrich_cache_write_failed", error=str(exc))
+
+
+# ---------------------------------------------------------------------------
+# Validation — LCOM4 before/after self-check (Extract Class)
+# ---------------------------------------------------------------------------
+
+
+def _validate_extract_class(
+ content: str, file_path: str, evidence: dict[str, Any]
+) -> dict[str, Any]:
+ """Re-walk the generated classes and compare LCOM4 against the original.
+
+ A real Extract Class lowers the worst per-class LCOM4 (each split class
+ should be cohesive, LCOM4 ~= 1) and yields >= 2 classes. Best-effort: any
+ parse/walk failure degrades to ``status="skipped"`` rather than raising.
+ """
+ language = _language_for(file_path)
+ if language is None:
+ return {"status": "skipped", "reason": f"no walker for {Path(file_path).suffix}"}
+
+ code = _extract_code_blocks(content, language)
+ if not code.strip():
+ return {"status": "skipped", "reason": "no parseable code blocks in response"}
+
+ try:
+ from repowise.core.analysis.health.complexity import walk_file
+
+ fc = walk_file(f"generated{Path(file_path).suffix}", language, code.encode())
+ except Exception as exc: # walker is best-effort here
+ return {"status": "skipped", "reason": f"walk failed: {exc}"}
+
+ classes = list(getattr(fc, "classes", []) or [])
+ if not classes:
+ 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]
+ after_max = max((c.lcom4 for c in classes), default=None)
+ improved = (
+ isinstance(before, int)
+ and after_max is not None
+ and after_max < before
+ and len(classes) >= 2
+ )
+ return {
+ "status": "checked",
+ "before_lcom4": before,
+ "after_classes": after,
+ "after_max_lcom4": after_max,
+ "class_count": len(classes),
+ "improved": bool(improved),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+
+async def enrich_suggestion(
+ suggestion: Any,
+ *,
+ provider: BaseProvider,
+ repo_path: Path,
+ cache_dir: Path | None = None,
+ use_cache: bool = True,
+ validate: bool = True,
+ max_tokens: int = 8000,
+) -> EnrichmentResult:
+ """Generate refactored code + a diff for one deterministic suggestion.
+
+ On-demand only. Gathers the plan's source spans off *repo_path*, prompts
+ *provider*, parses the diff, runs the Extract Class self-check, and caches
+ the result by a content hash so an unchanged plan never regenerates.
+ """
+ spans = _gather_spans(suggestion, repo_path)
+ model = getattr(provider, "model_name", "") or ""
+ provider_name = getattr(provider, "provider_name", "") or ""
+ suggestion_id = getattr(suggestion, "id", None)
+
+ cdir = cache_dir or _cache_dir(repo_path)
+ key = _cache_key(suggestion, spans, model)
+ if use_cache:
+ cached = _read_cache(cdir, key)
+ if cached is not None:
+ return cached
+
+ system = _SYSTEM_PROMPT + "\n" + _TYPE_INSTRUCTIONS.get(suggestion.refactoring_type, "")
+ user = _build_user_prompt(suggestion, spans)
+ response = await provider.generate(
+ system,
+ user,
+ max_tokens=max_tokens,
+ temperature=0.1,
+ cache_hints=(CacheHint(segment="system"),),
+ )
+
+ content = response.content or ""
+ diff = _extract_diff(content)
+ validation: dict[str, Any] = {}
+ if validate and suggestion.refactoring_type == "extract_class":
+ validation = _validate_extract_class(
+ content, suggestion.file_path, suggestion.evidence or {}
+ )
+
+ result = EnrichmentResult(
+ refactoring_type=suggestion.refactoring_type,
+ file_path=suggestion.file_path,
+ target_symbol=suggestion.target_symbol,
+ suggestion_id=suggestion_id,
+ content=content,
+ diff=diff,
+ provider=provider_name,
+ model=model,
+ cached=False,
+ input_tokens=getattr(response, "input_tokens", 0) or 0,
+ output_tokens=getattr(response, "output_tokens", 0) or 0,
+ validation=validation,
+ spans=[{"file": s.file, "line_start": s.start_line, "line_end": s.end_line} for s in spans],
+ )
+ if use_cache:
+ _write_cache(cdir, key, result)
+ return result
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index c96d8254b..0dbf019f5 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -58,6 +58,7 @@ from repowise.server.mcp_server.tool_dependency import get_dependency_path
from repowise.server.mcp_server.tool_flows import get_execution_flows
from repowise.server.mcp_server.tool_health import get_health
from repowise.server.mcp_server.tool_overview import get_overview
+from repowise.server.mcp_server.tool_refactoring import generate_refactoring_code
from repowise.server.mcp_server.tool_repos import list_repos
from repowise.server.mcp_server.tool_risk import get_risk
from repowise.server.mcp_server.tool_search import search_codebase
@@ -137,6 +138,7 @@ __all__ = [
"get_dependency_path",
"get_execution_flows",
"get_health",
+ "generate_refactoring_code",
"get_overview",
"get_risk",
"get_symbol",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index dc714e519..fd54c3cd0 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -74,6 +74,9 @@ def _serialize_refactoring(r: Any) -> dict[str, Any]:
return {}
return {
+ # The persisted row id — pass it to ``generate_refactoring_code`` to
+ # turn this plan into actual code + a diff (opt-in).
+ "id": getattr(r, "id", None),
"refactoring_type": r.refactoring_type,
"file_path": r.file_path,
"target_symbol": r.target_symbol,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
new file mode 100644
index 000000000..ba558002e
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py
@@ -0,0 +1,118 @@
+"""MCP tool: generate_refactoring_code — opt-in plan -> code + diff.
+
+The deterministic refactoring layer surfaces structured plans through
+``get_health(include=["refactoring"])``; each plan carries an ``id``. This tool
+takes one such id and asks the configured LLM to produce the actual refactored
+code and a unified diff, grounded on the plan plus the real source spans it
+references. It is strictly opt-in (gated on ``refactoring.llm.enabled``) and
+needs the working tree on disk, so it is a local-server capability.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from repowise.core.persistence.crud import get_refactoring_suggestion
+from repowise.core.persistence.database import get_session
+from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context
+from repowise.server.mcp_server._meta import build_meta as _build_meta
+
+
+def _row_to_suggestion(row: Any) -> Any:
+ """Re-hydrate a persisted ORM row into a ``RefactoringSuggestion`` dataclass.
+
+ Mirrors the web router's adapter; the enrichment engine reads the open
+ ``plan`` / ``evidence`` / ``blast_radius`` dicts, which the DB stores as
+ ``*_json`` text.
+ """
+ from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+
+ def _loads(value: Any) -> dict[str, Any]:
+ if not value:
+ return {}
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+ sug = RefactoringSuggestion(
+ refactoring_type=row.refactoring_type,
+ file_path=row.file_path,
+ target_symbol=row.target_symbol,
+ line_start=row.line_start,
+ line_end=row.line_end,
+ plan=_loads(row.plan_json),
+ evidence=_loads(row.evidence_json),
+ impact_delta=row.impact_delta,
+ effort_bucket=row.effort_bucket,
+ blast_radius=_loads(row.blast_radius_json),
+ confidence=row.confidence,
+ source_biomarker=row.source_biomarker,
+ )
+ sug.id = row.id # type: ignore[attr-defined]
+ return sug
+
+
+async def generate_refactoring_code(suggestion_id: str, repo: str | None = None) -> dict:
+ """Generate refactored code + a unified diff for one refactoring plan.
+
+ Opt-in code generation: turns a deterministic plan (from
+ ``get_health(include=["refactoring"])`` — use a plan's ``id``) into the
+ actual named code and a git-style diff, grounded on the plan plus the real
+ source spans it references. For Extract Class the result carries an LCOM4
+ before/after self-check.
+
+ Disabled by default — returns an ``error`` unless ``refactoring.llm.enabled``
+ is set in the repo's ``.repowise/config.yaml``. Uses the repo's configured
+ provider/model (BYO key) and caches by a content hash, so an unchanged plan
+ never regenerates.
+
+ Args:
+ suggestion_id: The ``id`` of a plan from ``get_health(... "refactoring")``.
+ repo: Repo alias / id / path.
+ """
+ from repowise.core.analysis.health.refactoring.llm import (
+ build_enrichment_provider,
+ enrich_suggestion,
+ llm_enrichment_enabled,
+ )
+ from repowise.core.repo_config import load_repo_config
+
+ ctx = await _resolve_repo_context(repo)
+ repo_path = Path(ctx.path)
+
+ if not llm_enrichment_enabled(load_repo_config(repo_path)):
+ return {
+ "error": "disabled",
+ "detail": (
+ "Refactoring code generation is opt-in. Set 'refactoring.llm.enabled: "
+ "true' in .repowise/config.yaml to enable it."
+ ),
+ }
+
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session, repo)
+ row = await get_refactoring_suggestion(session, repository.id, suggestion_id)
+ if row is None:
+ return {
+ "error": "not_found",
+ "detail": f"No refactoring plan with id {suggestion_id!r} in this repo.",
+ "_meta": _build_meta(repository=repository),
+ }
+ sug = _row_to_suggestion(row)
+ meta = _build_meta(repository=repository)
+
+ try:
+ provider = build_enrichment_provider(repo_path)
+ except ValueError as exc:
+ return {"error": "no_provider", "detail": str(exc), "_meta": meta}
+
+ result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path)
+ payload = result.to_dict()
+ payload["_meta"] = meta
+ return payload
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 1e5b51bfa..317035343 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -14,6 +14,7 @@ checkout — the same property the C4 endpoints rely on.
from __future__ import annotations
import json
+from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -29,6 +30,8 @@ def blast_files(sug: RefactoringSuggestion) -> list[str]:
carries — used to scope the detail endpoint's centrality lookup."""
files = (sug.blast_radius or {}).get("files")
return [f for f in files if isinstance(f, str)] if isinstance(files, list) else []
+
+
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
@@ -121,7 +124,9 @@ def _row_to_suggestion(row: Any) -> RefactoringSuggestion:
return sug
-def _to_response(sug: RefactoringSuggestion, centrality: dict[str, float]) -> RefactoringPlanResponse:
+def _to_response(
+ sug: RefactoringSuggestion, centrality: dict[str, float]
+) -> RefactoringPlanResponse:
return RefactoringPlanResponse(
id=getattr(sug, "id", ""),
refactoring_type=sug.refactoring_type,
@@ -158,7 +163,8 @@ async def _centrality_map(session: AsyncSession, repo_id: str) -> dict[str, floa
async def get_refactoring_targets(
repo_id: str,
refactoring_type: str | None = Query(
- None, description="Filter to one type: extract_class | extract_helper | move_method | break_cycle"
+ None,
+ description="Filter to one type: extract_class | extract_helper | move_method | break_cycle",
),
min_confidence: str | None = Query(None, description="low | medium | high"),
session: AsyncSession = Depends(get_db_session),
@@ -223,3 +229,90 @@ async def get_refactoring_plan(
# carries the caller rollup the list ranked on.
rank_suggestions([sug], centrality=centrality)
return _to_response(sug, centrality)
+
+
+# ---------------------------------------------------------------------------
+# Opt-in LLM enrichment — plan -> generated code + diff
+# ---------------------------------------------------------------------------
+
+
+class GenerateCodeRequest(BaseModel):
+ """Optional per-call overrides for the enrichment provider/model."""
+
+ provider: str | None = None
+ model: str | None = None
+
+
+class GenerateCodeResponse(BaseModel):
+ """Generated refactored code + diff for one plan, with the self-check."""
+
+ suggestion_id: str | None = None
+ refactoring_type: str
+ file_path: str
+ target_symbol: str
+ content: str
+ diff: str
+ provider: str
+ model: str
+ cached: bool
+ input_tokens: int
+ output_tokens: int
+ validation: dict[str, Any] = Field(default_factory=dict)
+ spans: list[dict[str, Any]] = Field(default_factory=list)
+
+
+ "/{repo_id}/refactoring/{suggestion_id}/generate-code",
+ response_model=GenerateCodeResponse,
+)
+async def generate_refactoring_code(
+ repo_id: str,
+ suggestion_id: str,
+ body: GenerateCodeRequest | None = None,
+ session: AsyncSession = Depends(get_db_session),
+) -> GenerateCodeResponse:
+ """Generate the refactored code + a unified diff for one plan, on demand.
+
+ Strictly opt-in: returns 403 unless ``refactoring.llm.enabled`` is set in the
+ repo's ``.repowise/config.yaml``. Needs the working tree on disk (it reads
+ the plan's real source spans), so this is a local-``serve`` capability, not a
+ hosted one — it returns 404 when the repo has no accessible checkout.
+ """
+ from repowise.core.analysis.health.refactoring.llm import (
+ build_enrichment_provider,
+ enrich_suggestion,
+ llm_enrichment_enabled,
+ )
+ from repowise.core.repo_config import load_repo_config
+
+ 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",
+ )
+
+ if not llm_enrichment_enabled(load_repo_config(repo_path)):
+ raise HTTPException(
+ status_code=403,
+ detail="refactoring code generation is disabled (set refactoring.llm.enabled)",
+ )
+
+ row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)
+ if row is None:
+ raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")
+ sug = _row_to_suggestion(row)
+
+ body = body or GenerateCodeRequest()
+ try:
+ provider = build_enrichment_provider(
+ repo_path, provider_name=body.provider, model=body.model
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path)
+ return GenerateCodeResponse(**result.to_dict())
diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.py
new file mode 100644
index 000000000..e37071517
--- /dev/null
+++ b/tests/unit/health/test_refactoring_enrich.py
@@ -0,0 +1,248 @@
+"""Unit tests for the opt-in LLM refactoring-enrichment engine.
+
+Uses ``MockProvider`` so no API calls happen. Covers: per-type source
+gathering, prompt assembly, on-disk caching, diff extraction, the Extract
+Class LCOM4 self-check, and the config gate.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.health.refactoring.llm import (
+ EnrichmentResult,
+ enrich_suggestion,
+ llm_enrichment_enabled,
+)
+from repowise.core.analysis.health.refactoring.llm.enrich import (
+ _build_user_prompt,
+ _extract_diff,
+ _gather_spans,
+)
+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+from repowise.core.providers.llm.base import GeneratedResponse
+from repowise.core.providers.llm.mock import MockProvider
+
+
+def _extract_class_suggestion() -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="extract_class",
+ file_path="pkg/example.py",
+ target_symbol="GodClass",
+ line_start=1,
+ line_end=20,
+ plan={
+ "groups": [
+ {"name": None, "methods": ["get"], "fields": ["x"]},
+ {"name": None, "methods": ["put"], "fields": ["y"]},
+ ]
+ },
+ evidence={"lcom4": 2, "method_count": 4, "field_count": 2, "wmc": 12},
+ impact_delta=2.5,
+ effort_bucket="L",
+ blast_radius={"dependents_count": 0},
+ confidence="high",
+ source_biomarker="low_cohesion",
+ )
+
+
+def _write_source(repo: Path, rel: str, body: str) -> None:
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(body, encoding="utf-8")
+
+
+# ---------------------------------------------------------------------------
+# Source gathering
+# ---------------------------------------------------------------------------
+
+
+def test_gather_spans_reads_target_span(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "\n".join(f"line {i}" for i in range(1, 31)))
+ spans = _gather_spans(_extract_class_suggestion(), tmp_path)
+ assert len(spans) == 1
+ assert spans[0].file == "pkg/example.py"
+ assert spans[0].start_line == 1 and spans[0].end_line == 20
+ assert "line 1" in spans[0].source and "line 20" in spans[0].source
+
+
+def test_gather_spans_extract_helper_reads_every_occurrence(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/a.py", "\n".join(f"a{i}" for i in range(1, 41)))
+ _write_source(tmp_path, "pkg/b.py", "\n".join(f"b{i}" for i in range(1, 41)))
+ sug = RefactoringSuggestion(
+ refactoring_type="extract_helper",
+ file_path="pkg/a.py",
+ target_symbol="dup",
+ line_start=5,
+ line_end=15,
+ plan={
+ "occurrences": [
+ {"file": "pkg/a.py", "line_start": 5, "line_end": 15},
+ {"file": "pkg/b.py", "line_start": 10, "line_end": 20},
+ ],
+ "suggested_site": {"module": "pkg", "directory": "pkg"},
+ "duplicated_lines": 10,
+ },
+ evidence={"occurrence_count": 2, "duplicated_lines": 10, "co_change_count": 4},
+ impact_delta=0.6,
+ effort_bucket="M",
+ blast_radius={"files": ["pkg/a.py", "pkg/b.py"]},
+ confidence="high",
+ source_biomarker="dry_violation",
+ )
+ spans = _gather_spans(sug, tmp_path)
+ files = {s.file for s in spans}
+ assert files == {"pkg/a.py", "pkg/b.py"}
+
+
+def test_gather_spans_skips_path_escape(tmp_path: Path) -> None:
+ sug = _extract_class_suggestion()
+ sug.file_path = "../outside.py"
+ assert _gather_spans(sug, tmp_path) == []
+
+
+def test_user_prompt_carries_plan_and_source(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "class GodClass:\n pass\n")
+ sug = _extract_class_suggestion()
+ sug.line_end = 2
+ spans = _gather_spans(sug, tmp_path)
+ prompt = _build_user_prompt(sug, spans)
+ assert "EXTRACT CLASS" in prompt
+ assert "GodClass" in prompt
+ assert "Structured plan" in prompt
+ assert "class GodClass" in prompt
+
+
+# ---------------------------------------------------------------------------
+# Diff extraction
+# ---------------------------------------------------------------------------
+
+
+def test_extract_diff_pulls_fenced_block() -> None:
+ content = "Summary\n\n```diff\n--- a/x.py\n+++ b/x.py\n@@\n-old\n+new\n```\n"
+ diff = _extract_diff(content)
+ assert diff.startswith("--- a/x.py")
+ assert "+new" in diff
+
+
+def test_extract_diff_absent_returns_empty() -> None:
+ assert _extract_diff("no diff here") == ""
+
+
+# ---------------------------------------------------------------------------
+# End-to-end enrichment + caching
+# ---------------------------------------------------------------------------
+
+
+async def test_enrich_returns_result_and_caches(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "class GodClass:\n pass\n" + "x = 1\n" * 18)
+ provider = MockProvider(responses=[GeneratedResponse("done\n```diff\n+a\n```", 10, 5)])
+ sug = _extract_class_suggestion()
+
+ result = await enrich_suggestion(sug, provider=provider, repo_path=tmp_path)
+ assert isinstance(result, EnrichmentResult)
+ assert result.refactoring_type == "extract_class"
+ assert result.provider == "mock"
+ assert result.diff == "+a"
+ assert result.cached is False
+ assert provider.call_count == 1
+ assert result.spans and result.spans[0]["file"] == "pkg/example.py"
+
+ # Second call with the same plan + source + model is served from cache.
+ cached = await enrich_suggestion(sug, provider=provider, repo_path=tmp_path)
+ assert cached.cached is True
+ assert provider.call_count == 1 # no second generate()
+
+
+async def test_enrich_no_cache_regenerates(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "class GodClass:\n pass\n")
+ provider = MockProvider(responses=[GeneratedResponse("a", 1, 1), GeneratedResponse("b", 1, 1)])
+ sug = _extract_class_suggestion()
+ await enrich_suggestion(sug, provider=provider, repo_path=tmp_path, use_cache=False)
+ await enrich_suggestion(sug, provider=provider, repo_path=tmp_path, use_cache=False)
+ assert provider.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# LCOM4 self-check (Extract Class)
+# ---------------------------------------------------------------------------
+
+
+_TWO_COHESIVE_CLASSES = """\
+Here is the split.
+
+```python
+class Getter:
+ def __init__(self):
+ self.x = 0
+
+ def get(self):
+ return self.x
+
+
+class Putter:
+ def __init__(self):
+ self.y = 0
+
+ def put(self, v):
+ self.y = v
+```
+"""
+
+
+async def test_extract_class_self_check_reports_improvement(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "class GodClass:\n pass\n")
+ provider = MockProvider(responses=[GeneratedResponse(_TWO_COHESIVE_CLASSES, 10, 50)])
+ result = await enrich_suggestion(
+ _extract_class_suggestion(), provider=provider, repo_path=tmp_path
+ )
+ v = result.validation
+ assert v["status"] == "checked"
+ assert v["before_lcom4"] == 2
+ assert v["class_count"] == 2
+ assert v["after_max_lcom4"] == 1
+ assert v["improved"] is True
+
+
+async def test_self_check_skipped_when_no_code_blocks(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/example.py", "class GodClass:\n pass\n")
+ provider = MockProvider(responses=[GeneratedResponse("prose only, no code", 5, 5)])
+ result = await enrich_suggestion(
+ _extract_class_suggestion(), provider=provider, repo_path=tmp_path
+ )
+ assert result.validation["status"] == "skipped"
+
+
+async def test_self_check_skipped_for_non_extract_class(tmp_path: Path) -> None:
+ _write_source(tmp_path, "pkg/a.py", "x = 1\n")
+ sug = RefactoringSuggestion(
+ refactoring_type="break_cycle",
+ file_path="pkg/a.py",
+ target_symbol="cycle",
+ 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},
+ impact_delta=0.0,
+ effort_bucket="M",
+ blast_radius={"files": ["pkg/a.py", "pkg/b.py"]},
+ confidence="medium",
+ )
+ provider = MockProvider(responses=[GeneratedResponse("fix", 1, 1)])
+ result = await enrich_suggestion(sug, provider=provider, repo_path=tmp_path)
+ assert result.validation == {}
+
+
+# ---------------------------------------------------------------------------
+# Config gate
+# ---------------------------------------------------------------------------
+
+
+def test_llm_enrichment_enabled_gate() -> None:
+ assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": True}}}) is True
+ assert llm_enrichment_enabled({"refactoring": {"llm": {"enabled": False}}}) is False
+ assert llm_enrichment_enabled({"refactoring": {}}) is False
+ assert llm_enrichment_enabled({}) is False
diff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.py
new file mode 100644
index 000000000..263cb596c
--- /dev/null
+++ b/tests/unit/server/mcp/test_refactoring.py
@@ -0,0 +1,120 @@
+"""Unit tests for the generate_refactoring_code MCP tool (opt-in enrichment).
+
+Uses the ``mock`` provider (no API calls) and a real temp checkout so the tool
+can read the plan's source spans and honor the config gate.
+"""
+
+from __future__ import annotations
+
+import tempfile
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.models import Repository
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+
+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)
+ cfg = "provider: mock\n"
+ if enabled:
+ cfg += "refactoring:\n llm:\n enabled: true\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"
+ )
+
+ async with factory() as session:
+ session.add(
+ Repository(
+ id="r1",
+ name="mcp-enrich",
+ url="https://github.com/example/mcp-enrich",
+ local_path=str(repo_dir),
+ default_branch="main",
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+ await session.flush()
+ await crud.save_refactoring_suggestions(
+ session,
+ "r1",
+ [
+ {
+ "refactoring_type": "extract_class",
+ "file_path": "pkg/leaf.py",
+ "target_symbol": "GodClass",
+ "line_start": 1,
+ "line_end": 3,
+ "plan": {"groups": [{"name": None, "methods": ["a"], "fields": []}]},
+ "evidence": {"lcom4": 2, "method_count": 1, "field_count": 0, "wmc": 1},
+ "impact_delta": 1.0,
+ "effort_bucket": "S",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "high",
+ "source_biomarker": "low_cohesion",
+ },
+ ],
+ )
+ await session.commit()
+ sid = (await crud.get_refactoring_suggestions(session, "r1"))[0].id
+ return repo_dir, sid
+
+
+def _mcp_globals(factory):
+ import repowise.server.mcp_server as mcp_mod
+
+ saved_factory = mcp_mod._session_factory
+ saved_path = mcp_mod._repo_path
+ yield mcp_mod
+ mcp_mod._session_factory = saved_factory
+ mcp_mod._repo_path = saved_path
+
+
+async def test_generate_code_happy_path(factory, _mcp_globals) -> None:
+ from repowise.server.mcp_server import generate_refactoring_code
+
+ repo_dir, sid = await _setup(factory, enabled=True)
+ _mcp_globals._session_factory = factory
+ _mcp_globals._repo_path = str(repo_dir)
+
+ result = await generate_refactoring_code(sid)
+ assert "error" not in result
+ assert result["refactoring_type"] == "extract_class"
+ assert result["provider"] == "mock"
+ assert result["content"]
+ assert "_meta" in result
+
+
+async def test_generate_code_disabled(factory, _mcp_globals) -> None:
+ from repowise.server.mcp_server import generate_refactoring_code
+
+ repo_dir, sid = await _setup(factory, enabled=False)
+ _mcp_globals._session_factory = factory
+ _mcp_globals._repo_path = str(repo_dir)
+
+ result = await generate_refactoring_code(sid)
+ assert result["error"] == "disabled"
+
+
+async def test_generate_code_unknown_id(factory, _mcp_globals) -> None:
+ from repowise.server.mcp_server import generate_refactoring_code
+
+ repo_dir, _ = await _setup(factory, enabled=True)
+ _mcp_globals._session_factory = factory
+ _mcp_globals._repo_path = str(repo_dir)
+
+ result = await generate_refactoring_code("deadbeef")
+ assert result["error"] == "not_found"
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index baf89212a..478eabfb0 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -225,3 +225,84 @@ async def test_min_confidence_filters(client: AsyncClient, app) -> None:
# Only the two high-confidence plans survive (extract_class, extract_helper).
assert body["summary"]["total"] == 2
assert {p["refactoring_type"] for p in body["plans"]} == {"extract_class", "extract_helper"}
+
+
+# ---------------------------------------------------------------------------
+# POST /generate-code (opt-in LLM enrichment)
+# ---------------------------------------------------------------------------
+
+
+async def _seed_enrich_repo(client: AsyncClient, app, *, enabled: bool) -> tuple[str, str]:
+ """A repo with a real checkout (config + one source file) and one plan.
+
+ Uses the ``mock`` provider so ``build_enrichment_provider`` resolves a
+ MockProvider with no API key. Returns ``(repo_id, suggestion_id)``."""
+ repo_dir = Path(tempfile.mkdtemp()) / "enrich-repo"
+ (repo_dir / "pkg").mkdir(parents=True, exist_ok=True)
+ (repo_dir / ".git").mkdir(exist_ok=True)
+ (repo_dir / ".repowise").mkdir(exist_ok=True)
+ cfg = "provider: mock\n"
+ if enabled:
+ cfg += "refactoring:\n llm:\n enabled: true\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)),
+ encoding="utf-8",
+ )
+
+ resp = await client.post(
+ "/api/repos",
+ json={
+ "name": "enrich-repo",
+ "local_path": str(repo_dir),
+ "url": "https://github.com/example/enrich-repo",
+ },
+ )
+ assert resp.status_code == 201
+ 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 session.commit()
+ rows = await crud.get_refactoring_suggestions(session, repo_id)
+ suggestion_id = rows[0].id
+ return repo_id, suggestion_id
+
+
+async def test_generate_code_happy_path(client: AsyncClient, app) -> None:
+ repo_id, sid = await _seed_enrich_repo(client, app, enabled=True)
+ resp = await client.post(f"/api/repos/{repo_id}/refactoring/{sid}/generate-code", json={})
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["refactoring_type"] == "extract_class"
+ assert body["target_symbol"] == "GodClass"
+ assert body["provider"] == "mock"
+ assert body["content"] # the mock returned something
+ assert body["spans"] and body["spans"][0]["file"] == "pkg/leaf.py"
+
+
+async def test_generate_code_disabled_returns_403(client: AsyncClient, app) -> None:
+ repo_id, sid = await _seed_enrich_repo(client, app, enabled=False)
+ resp = await client.post(f"/api/repos/{repo_id}/refactoring/{sid}/generate-code", json={})
+ assert resp.status_code == 403
+
+
+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