Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(refactor): surface Split File plans in the web UI and code-gen (#608)
Raghav Chamadiya679c7ef3109b
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex d134b34ff..199812366 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -10,7 +10,7 @@ Python over tree-sitter + git data, designed to finish in under 30 seconds on a3 000-file repo.<div align="center">-<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle) your agent executes" width="100%" />+<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — 25 deterministic biomarkers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle, Split File) your agent executes" width="100%" /></div>Code health runs as a loop: **measure** every file across three signals,@@ -561,7 +561,7 @@ A health score tells you a file is in trouble; a refactoring target names the**specific** fix. Repowise emits one structured `RefactoringSuggestion` peropportunity, computed deterministically during the health pass from data it hasalready produced — the call graph, the class cohesion model, the clone pairs, and-git co-change. No re-parse, no LLM, inside the same <30s budget. Four detectors+git co-change. No re-parse, no LLM, inside the same <30s budget. Five detectorsship today:| Type | What it names | Built from |@@ -570,6 +570,7 @@ ship today:| **Extract Helper** | A clone's exact occurrences and where the shared helper should live. | Rabin–Karp clone pairs (line ranges + token count + co-change); extraction site = community centroid of the files. Transitive clones are clustered into one suggestion, not pairwise nags. || **Move Method** | A feature-envy method and the class it actually belongs to. | Jaccard distance of the method's entity set (fields/methods it touches) to each class over the call graph; fires only when a foreign class is clearly nearer than its own. || **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | Strongly-connected component → greedy minimum feedback arc set over the real import edges. |+| **Split File** | The cohesive files an oversized module should decompose into — which symbols move where, plus the import edits in every dependent. | Community detection (Leiden/Louvain) over a weighted intra-file symbol graph, gated on partition **modularity**. Language-agnostic (reads `defines`/`calls` edges); the file-level analog of Extract Class. |Each suggestion is **structured data, not a string**: a `plan` (the split groups,the move target, the cut edges), the `evidence` that justifies it (LCOM4=3, the@@ -593,8 +594,9 @@ get_health(targets=["module:src.api"]) # everything in a module```The web **Refactoring** tab renders each plan as a card (split groups as a tree,-move arrow, clone occurrences with line links) with a **copy-to-agent** prompt and-an opt-in **Generate code** action that expands a plan into generated code plus a+move arrow, clone occurrences with line links, file-split groups with their+residual core and import-rewrite list) with a **copy-to-agent** prompt and an+opt-in **Generate code** action that expands a plan into generated code plus aunified diff. Code generation is strictly opt-in (`refactoring.llm.enabled`) andnever runs in the indexing hot path. Full reference:**[docs/REFACTORING.md](REFACTORING.md)**.@@ -799,7 +801,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts) · 7.0| Health trend tracking | ✅ | ✅ | ❌ | ❌ || Declining health alerts | ✅ | ✅ | ❌ | ❌ || Refactoring recommendations | ✅ deterministic | ✅ | ❌ | ❌ |-| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Move Method / Break Cycle, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file |+| Concrete cross-file refactoring plans | ✅ Extract Class / Helper / Move Method / Break Cycle / Split File, graph-aware + blast radius | ⚠️ within-function only | ❌ | ✅ within-file || Free for internal use | ✅ AGPL-3.0 | ❌ $15–30/author | ✅ public repos | ❌ |## See alsodiff --git a/docs/INTELLIGENCE_LAYERS.md b/docs/INTELLIGENCE_LAYERS.mdindex b78ff7050..4285704e3 100644--- a/docs/INTELLIGENCE_LAYERS.md+++ b/docs/INTELLIGENCE_LAYERS.md@@ -201,11 +201,12 @@ repowise status # one-line summary in the status reportHealth` and `Predicted Decline` alerts.- **Refactoring plans** — deterministic, structured, **graph-aware**: ExtractClass (LCOM4 cohesion split), Extract Helper (clone dedup), Move Method (feature- envy), and Break Cycle (minimum feedback arc set), each carrying its concrete- plan, recovered impact, and blast radius. Ranked by `impact × centrality ×- blast radius`, on the dashboard **Refactoring** tab, via `repowise health- --refactoring-targets`, and via `get_health(include=["refactoring"])`. An opt-in- LLM pass expands any plan into generated code + a diff. See+ envy), Break Cycle (minimum feedback arc set), and Split File (modularity-gated+ module decomposition with the import-rewrite blast radius), each carrying its+ concrete plan, recovered impact, and blast radius. Ranked by `impact ×+ centrality × blast radius`, on the dashboard **Refactoring** tab, via `repowise+ health --refactoring-targets`, and via `get_health(include=["refactoring"])`. An+ opt-in LLM pass expands any plan into generated code + a diff. See[`docs/REFACTORING.md`](REFACTORING.md).- **Per-file overrides** via `.repowise/health-rules.json`.diff --git a/docs/REFACTORING.md b/docs/REFACTORING.mdindex 81dff5ccd..f50066c75 100644--- a/docs/REFACTORING.md+++ b/docs/REFACTORING.md@@ -5,9 +5,10 @@ the specific fix.** Every other tool stops at the score, or prints the samestatic sentence for every god class in every repo. repowise emits one structuredplan per opportunity — *split `GraphBuilder` into these three cohesive groups*,*move `resolve_call` to the `resolvers` class where its calls actually land*,-*break the `pipeline ↔ update` import cycle by inverting this one edge* — computed-deterministically from the same graph, class model, and git data the score is-built on.+*break the `pipeline ↔ update` import cycle by inverting this one edge*,+*decompose this 900-line module into these four files and rewrite the imports in+the six that depend on it* — computed deterministically from the same graph,+class model, and git data the score is built on.```bashrepowise health --refactoring-targets # ranked plans, biggest win for least effort@@ -22,7 +23,7 @@ LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop — biomarkers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" /></div>-## The four detectors+## The five detectorsEach detector is a self-contained module registered into a registry (adding arefactoring type is a new file + a registry entry, like the biomarker registry).@@ -35,10 +36,18 @@ one** — and produces stable-sorted, deterministic output.| **Extract Helper** | A clone's exact occurrences and where the shared helper belongs. | Rabin–Karp clone pairs (line ranges, token count, co-change). The extraction site is the community centroid of the involved files; transitive clones (A↔B, B↔C) are clustered into one suggestion, not pairwise nags. || **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. || **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. |+| **Split File** | The cohesive files an oversized module should decompose into — which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |The algorithms are derived from public academic literature (Fokaefs-Tsantalis-HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking),-not from any product.+HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking,+Newman-Girvan modularity for module decomposition), not from any product.++**Split File is the cross-file wedge made concrete.** It is language-agnostic —+it reads only the already-built graph (`defines` / `calls` edges), so it works+the same on every language with call resolution, and it covers the gap LCOM4+leaves for Go (top-level functions, not class methods). Splitting Go files in the+same package is near-zero blast radius (no import edits); Python/TS get a+back-compat re-export shim, surfaced as `shim_required` on the plan.## Anatomy of a suggestion@@ -48,10 +57,10 @@ web).| Field | Meaning ||-------|---------|-| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` |+| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` || `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |-| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, or the cycle + `cut_edges`. |-| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size. |+| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, or the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`. |+| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. || `impact_delta` | The health score the refactoring would recover (the deduction of the biomarker it answers); `0` for the graph-native types that answer no biomarker. || `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. || `blast_radius` | What else must move: the callers, co-change partners, and importing files. |@@ -76,8 +85,8 @@ score = (1 + impact_delta)```A plan on a **central hub file outranks the same plan on a leaf**. Because the-impact-free graph-native types (Move Method, Break Cycle) still rank via-centrality and blast radius, they interleave fairly with the impact-bearing+impact-free graph-native types (Move Method, Break Cycle, Split File) still rank+via centrality and blast radius, they interleave fairly with the impact-bearingtypes rather than sinking below them. Ties break on type → file → target, so theorder is fully deterministic.@@ -107,10 +116,12 @@ GET /api/repos/{repo_id}/refactoring/{suggestion_id} # one plan + blast-r```The web **Refactoring** tab renders each plan as a card — the split groups as a-small tree, the move arrow, the clone occurrences with line links — over an-impact/effort quadrant, with per-type filter chips (URL-synced). Each card has a-**copy-to-agent** button that exports the structured plan + source spans + blast-radius as a prompt a coding agent can execute.+small tree, the move arrow, the clone occurrences with line links, the file-split+groups tree with its residual core and import-rewrite list — over an impact/effort+quadrant, with per-type filter chips (URL-synced) and a distinct accent color per+type carried consistently across the quadrant dots, card rails, and chips. Each+card has a **copy-to-agent** button that exports the structured plan + source+spans + blast radius as a prompt a coding agent can execute.## Opt-in code generation@@ -134,10 +145,12 @@ With `llm.enabled` set, the **Generate code** action on a plan card (or theendpoint below) gathers the plan's real source spans off the working tree, buildsa behavior-preservation prompt carrying the structured plan **plus thegraph/co-change context** a bare codegen tool throws away, and returns the-refactored code and a unified diff. For Extract Class it runs an **LCOM4-before/after self-check** (re-walking the generated classes) to report whether the-split actually improved cohesion. Results are cached on disk by a content hash-(plan + source + model), so the same plan never pays twice.+refactored code and a unified diff. Where a self-check is cheap and meaningful it+runs one: Extract Class re-walks the generated classes for an **LCOM4 before/after+delta**, and Split File re-walks the generated files to assert each is **below the+size floor** and the symbols are **partitioned with no duplication**. Results are+cached on disk by a content hash (plan + source + model), so the same plan never+pays twice.```textPOST /api/repos/{repo_id}/refactoring/{suggestion_id}/generate-codediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.pyindex cb471cb1c..e38e44157 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@@ -12,9 +12,11 @@ the indexing hot path:source + the graph/co-change context the deterministic layer alreadycomputed, and ask the configured provider for the refactored code and aunified 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.+3. Self-check the result where it is cheap and meaningful: Extract Class with an+ LCOM4 before/after delta (re-walk the generated classes), and Split File by+ re-walking the generated files to assert each is below the size floor and the+ symbols are partitioned with no duplication. Other types skip validation+ gracefully.Results are cached on disk by a content hash (plan + source + model), so thesame plan never pays for the same generation twice.@@ -25,6 +27,7 @@ from __future__ import annotationsimport hashlibimport jsonimport re+from collections import defaultdictfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Any@@ -39,6 +42,11 @@ log = structlog.get_logger(__name__)# total source-line caps, and a hard ceiling on how many spans we read._MAX_SPAN_LINES = 240_MAX_SPANS = 12+# Split File feeds the whole module (every symbol, so the model can partition+# them) — a larger cap than a single class/method span. A dependent file only+# contributes its import header, so it reads just the file head.+_MAX_FILE_SPAN_LINES = 1500+_MAX_IMPORT_HEAD_LINES = 60# Cache lives next to the other repo-local refactoring artifacts._CACHE_SUBDIR = ("refactoring", "enrich")@@ -90,7 +98,8 @@ class EnrichmentResult:cached: boolinput_tokens: intoutput_tokens: int- # LCOM4 before/after self-check (Extract Class only); ``{}`` when skipped.+ # Per-type self-check (Extract Class LCOM4 delta / Split File size+partition);+ # ``{}`` when the type has no check or it was 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)@@ -190,11 +199,14 @@ def build_enrichment_provider(# ----------------------------------------------------------------------------def _read_span(repo_path: Path, file: str, start: int, end: int) -> SourceSpan | None:+def _read_span(+ repo_path: Path, file: str, start: int, end: int, max_lines: int = _MAX_SPAN_LINES+) -> 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).+ any read error (the caller simply omits the span). *max_lines* bounds the+ span length (larger for a whole-module read, smaller for an import header)."""abs_path = (repo_path / file).resolve()try:@@ -213,36 +225,41 @@ def _read_span(repo_path: Path, file: str, start: int, end: int) -> SourceSpan |return Nones = max(1, min(start, total))e = max(s, min(end, total))- if (e - s + 1) > _MAX_SPAN_LINES:- e = s + _MAX_SPAN_LINES - 1+ if (e - s + 1) > max_lines:+ e = s + max_lines - 1return 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.+def _span_requests(suggestion: Any) -> list[tuple[str, int, int, int]]:+ """Per-type (file, start, end, max_lines) 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.+ move source/target files, the files on each cut edge, the dependent files of+ a split). 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]] = []+ requests: list[tuple[str, int, int, int]] = []- def _add(file: str | None, start: Any, end: Any) -> None:+ def _add(file: str | None, start: Any, end: Any, max_lines: int = _MAX_SPAN_LINES) -> None:if not file or len(requests) >= _MAX_SPANS:returntry:s = int(start) if start is not None else 1- e = int(end) if end is not None else s + _MAX_SPAN_LINES - 1+ e = int(end) if end is not None else s + max_lines - 1except (TypeError, ValueError):- s, e = 1, _MAX_SPAN_LINES- requests.append((file, s, e))+ s, e = 1, max_lines+ requests.append((file, s, e, max_lines))- # The headline target span (the class / method / site).+ # The headline target span. Split File needs the whole module (every symbol,+ # so the model can partition them); the others have a precise target span.if suggestion.file_path:- _add(suggestion.file_path, suggestion.line_start, suggestion.line_end)+ if rtype == "split_file":+ _add(suggestion.file_path, 1, _MAX_FILE_SPAN_LINES, _MAX_FILE_SPAN_LINES)+ else:+ _add(suggestion.file_path, suggestion.line_start, suggestion.line_end)if rtype == "extract_helper":for occ in plan.get("occurrences", []) or []:@@ -258,10 +275,17 @@ def _span_requests(suggestion: Any) -> list[tuple[str, int, int]]: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]] = []+ elif rtype == "split_file":+ # Each dependent file's import header, so the model can rewrite the+ # imports (and write the back-compat shim) precisely.+ blast = suggestion.blast_radius or {}+ for dep in (blast.get("dependent_files") or [])[:_MAX_SPANS]:+ if isinstance(dep, str):+ _add(dep, 1, _MAX_IMPORT_HEAD_LINES, _MAX_IMPORT_HEAD_LINES)++ # De-dup identical (file, start, end, max_lines) requests, order preserved.+ seen: set[tuple[str, int, int, int]] = set()+ unique: list[tuple[str, int, int, int]] = []for req in requests:if req not in seen:seen.add(req)@@ -271,8 +295,8 @@ def _span_requests(suggestion: Any) -> list[tuple[str, int, int]]: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)+ for file, start, end, max_lines in _span_requests(suggestion):+ span = _read_span(repo_path, file, start, end, max_lines)if span is not None:spans.append(span)return spans@@ -329,6 +353,18 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {"inversion, a shared interface/protocol module, or a local import as a ""last resort). Do not merge the files."),+ "split_file": (+ "Refactoring: SPLIT FILE. The module is too large and partitions into "+ "the cohesive groups in the plan. Create one new file per group at its "+ "'suggested_file' path, containing exactly that group's symbols, and "+ "remove them from the original. Keep the residual 'core' symbols in the "+ "original file. When 'shim_required' is true, leave a back-compat "+ "re-export shim in the original path (import and re-export the moved "+ "symbols) so existing imports keep working; when false (same-package "+ "languages such as Go) no import edits are needed. Never duplicate a "+ "symbol across files — each moves to exactly one place. Emit one fenced "+ "code block per file you create or change."+ ),}@@ -381,15 +417,16 @@ def _extract_diff(content: str) -> str: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.+def _code_block_list(content: str, language: str | None) -> list[str]:+ """Non-diff fenced code blocks (best-effort), one entry per block.Prefers blocks tagged with the target language but accepts untagged blocks;- always skips ``diff`` blocks (those are not parseable source).+ always skips ``diff`` blocks (those are not parseable source). Split File's+ self-check needs the blocks kept separate (one new file each)."""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"}+ aliases = {"py": "python", "ts": "typescript", "tsx": "typescript", "js": "javascript"}blocks: list[str] = []for tag, body in _CODE_FENCE.findall(content):norm = aliases.get(tag.lower(), tag.lower())@@ -397,8 +434,15 @@ def _extract_code_blocks(content: str, language: str | None) -> str:continueif wanted and norm and norm not in wanted:continue- blocks.append(body.strip())- return "\n\n".join(blocks)+ stripped = body.strip()+ if stripped:+ blocks.append(stripped)+ return blocks+++def _extract_code_blocks(content: str, language: str | None) -> str:+ """Concatenate non-diff fenced code blocks (best-effort) for the self-check."""+ return "\n\n".join(_code_block_list(content, language))def _language_for(file_path: str) -> str | None:@@ -515,6 +559,83 @@ def _validate_extract_class(}+# ---------------------------------------------------------------------------+# Validation — size + partition self-check (Split File)+# ---------------------------------------------------------------------------+++def _validate_split_file(content: str, file_path: str, plan: dict[str, Any]) -> dict[str, Any]:+ """Re-walk the generated files and assert the split is sound.++ A real Split File (1) yields >= 2 files, (2) each below the module-size+ floor that triggered the split, and (3) partitions the planned symbols with+ no duplication — a symbol moves to exactly one file. 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}"}++ blocks = _code_block_list(content, language)+ if len(blocks) < 2:+ return {"status": "skipped", "reason": "fewer than two code blocks in response"}++ try:+ from repowise.core.analysis.health.complexity import walk_file++ # Single source of truth for the size floor the detector gated on.+ from ..split_file import _MIN_FILE_NLOC as _FLOOR+ except Exception as exc:+ return {"status": "skipped", "reason": f"import failed: {exc}"}++ floor = _FLOOR++ # The top-level symbols the deterministic plan partitioned. Restricting the+ # duplication check to these excludes dunders / nested helpers that share a+ # name across files for legitimate reasons.+ planned: set[str] = set()+ for group in plan.get("groups", []) or []:+ if isinstance(group, dict):+ planned.update(str(s) for s in group.get("symbols", []) or [])+ residual = plan.get("residual") or {}+ if isinstance(residual, dict):+ planned.update(str(s) for s in residual.get("symbols", []) or [])++ suffix = Path(file_path).suffix+ per_file_nloc: list[int] = []+ name_files: dict[str, set[int]] = defaultdict(set)+ for idx, code in enumerate(blocks):+ try:+ fc = walk_file(f"generated_{idx}{suffix}", language, code.encode())+ except Exception:+ continue+ names = {+ sym.name for sym in list(fc.functions) + list(fc.classes) if getattr(sym, "name", None)+ }+ per_file_nloc.append(int(getattr(fc, "file_nloc", 0) or 0))+ for nm in names & planned:+ name_files[nm].add(idx)++ if not per_file_nloc:+ return {"status": "skipped", "reason": "no parseable code blocks in response"}++ max_nloc = max(per_file_nloc, default=0)+ all_below_floor = all(n < floor for n in per_file_nloc)+ duplicated = sorted(nm for nm, files in name_files.items() if len(files) > 1)+ partitioned = not duplicated+ improved = len(per_file_nloc) >= 2 and all_below_floor and partitioned+ return {+ "status": "checked",+ "file_count": len(per_file_nloc),+ "max_file_nloc": max_nloc,+ "size_floor": floor,+ "all_below_floor": all_below_floor,+ "duplicated_symbols": duplicated,+ "partitioned": partitioned,+ "improved": bool(improved),+ }++# ---------------------------------------------------------------------------# Entry point# ---------------------------------------------------------------------------@@ -565,6 +686,8 @@ async def enrich_suggestion(validation = _validate_extract_class(content, suggestion.file_path, suggestion.evidence or {})+ elif validate and suggestion.refactoring_type == "split_file":+ validation = _validate_split_file(content, suggestion.file_path, suggestion.plan or {})result = EnrichmentResult(refactoring_type=suggestion.refactoring_type,diff --git a/packages/ui/__tests__/refactoring/split-file-types.test.ts b/packages/ui/__tests__/refactoring/split-file-types.test.tsnew file mode 100644index 000000000..134447319--- /dev/null+++ b/packages/ui/__tests__/refactoring/split-file-types.test.ts@@ -0,0 +1,118 @@+import { describe, it, expect } from "vitest";+import {+ blastCount,+ blastFiles,+ generatedVerdict,+ planSynopsis,+ planWins,+ splitBlast,+ splitGroups,+ splitResidual,+ splitShimRequired,+ type GeneratedCode,+ type RefactoringPlan,+} from "../../src/refactoring/types";+import { typeMeta, TYPE_ORDER } from "../../src/refactoring/meta";++function splitPlan(overrides: Partial<RefactoringPlan> = {}): RefactoringPlan {+ return {+ id: "p1",+ refactoring_type: "split_file",+ file_path: "pkg/big.py",+ target_symbol: "big.py -> 2 files",+ line_start: null,+ line_end: null,+ plan: {+ groups: [+ { name: "parsing", symbols: ["parse_a", "parse_b"], suggested_file: "pkg/parsing.py" },+ { name: "rendering", symbols: ["render_a"], suggested_file: "pkg/rendering.py" },+ ],+ residual: { symbols: ["shared_helper"] },+ shim_required: true,+ },+ evidence: { file_nloc: 400, symbol_count: 8, group_count: 2, modularity: 0.5 },+ impact_delta: 0,+ effort_bucket: "L",+ blast_radius: { dependent_files: ["pkg/user.py", "pkg/other.py"], dependent_count: 2, import_rewrites: 2 },+ confidence: "high",+ source_biomarker: "",+ rank_score: 3.2,+ ...overrides,+ };+}++describe("split_file plan accessors", () => {+ it("reads groups, residual, and shim flag", () => {+ const plan = splitPlan();+ const groups = splitGroups(plan);+ expect(groups).toHaveLength(2);+ expect(groups[0]).toMatchObject({ name: "parsing", suggested_file: "pkg/parsing.py" });+ expect(groups[0]!.symbols).toEqual(["parse_a", "parse_b"]);+ expect(splitResidual(plan)).toEqual(["shared_helper"]);+ expect(splitShimRequired(plan)).toBe(true);+ });++ it("reads the dependent-file blast radius", () => {+ const blast = splitBlast(splitPlan());+ expect(blast.dependent_count).toBe(2);+ expect(blast.import_rewrites).toBe(2);+ expect(blast.dependent_files).toEqual(["pkg/user.py", "pkg/other.py"]);+ });++ it("feeds the generic blast helpers off the split shape", () => {+ const plan = splitPlan();+ expect(blastFiles(plan)).toEqual(["pkg/user.py", "pkg/other.py"]);+ expect(blastCount(plan)).toBe(2);+ });++ it("degrades gracefully on a malformed plan", () => {+ const plan = splitPlan({ plan: {}, blast_radius: {} });+ expect(splitGroups(plan)).toEqual([]);+ expect(splitResidual(plan)).toEqual([]);+ expect(splitShimRequired(plan)).toBe(false);+ expect(splitBlast(plan)).toEqual({ dependent_files: [], dependent_count: 0, import_rewrites: 0 });+ });++ it("summarizes for the card and the win band", () => {+ const plan = splitPlan();+ expect(planSynopsis(plan)).toBe("Split into 2 modules");+ const wins = planWins(plan).map((w) => w.label);+ expect(wins).toContain("2 focused modules from one file");+ expect(wins).toContain("2 dependent files to re-point");+ });++ it("frames a zero-import-edit (Go) split as a win", () => {+ const plan = splitPlan({+ plan: { groups: [{ name: null, symbols: ["a"], suggested_file: "pkg/a.go" }], residual: null, shim_required: false },+ blast_radius: { dependent_files: ["pkg/x.go"], dependent_count: 1, import_rewrites: 0 },+ });+ expect(planWins(plan).map((w) => w.label)).toContain("1 dependent, zero import edits");+ });+});++describe("split_file meta + self-check verdict", () => {+ it("has its own label, icon, and place in the legend order", () => {+ expect(typeMeta("split_file").label).toBe("Split File");+ expect(TYPE_ORDER).toContain("split_file");+ });++ it("reads a clean partition as a pass", () => {+ const result = {+ refactoring_type: "split_file",+ validation: { status: "checked", file_count: 2, max_file_nloc: 120, duplicated_symbols: [], improved: true },+ } as unknown as GeneratedCode;+ const verdict = generatedVerdict(result);+ expect(verdict).toMatchObject({ tone: "pass", label: "Cleanly partitioned" });+ expect(verdict?.detail).toContain("2 files");+ });++ it("reads a duplicated symbol as a fail", () => {+ const result = {+ refactoring_type: "split_file",+ validation: { status: "checked", file_count: 2, max_file_nloc: 120, duplicated_symbols: ["parse_a"], improved: false },+ } as unknown as GeneratedCode;+ const verdict = generatedVerdict(result);+ expect(verdict).toMatchObject({ tone: "fail", label: "Partition incomplete" });+ expect(verdict?.detail).toContain("1 symbol duplicated");+ });+});diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsxindex 88ece1e38..a8ee7bea9 100644--- a/packages/ui/src/refactoring/meta.tsx+++ b/packages/ui/src/refactoring/meta.tsx@@ -1,7 +1,7 @@"use client";import * as React from "react";-import { ArrowRightLeft, CopyMinus, Split, Unlink } from "lucide-react";+import { ArrowRightLeft, CopyMinus, FileStack, Split, Unlink } from "lucide-react";import type { Confidence, EffortBucket, RefactoringType } from "./types";export interface RefactoringTypeMeta {@@ -18,25 +18,31 @@ export const TYPE_META: Record<string, RefactoringTypeMeta> = {label: "Extract Class",blurb: "Split a low-cohesion class into focused, single-responsibility classes.",Icon: Split,- accentVar: "--color-accent-primary",+ accentVar: "--color-refactor-extract-class",},extract_helper: {label: "Extract Helper",blurb: "Dedupe a repeated block into one shared helper.",Icon: CopyMinus,- accentVar: "--color-success",+ accentVar: "--color-refactor-extract-helper",},move_method: {label: "Move Method",blurb: "Move a method to the class it actually belongs to.",Icon: ArrowRightLeft,- accentVar: "--color-caution",+ accentVar: "--color-refactor-move-method",},break_cycle: {label: "Break Cycle",blurb: "Cut the minimal import edge that closes a dependency cycle.",Icon: Unlink,- accentVar: "--color-warning",+ accentVar: "--color-refactor-break-cycle",+ },+ split_file: {+ label: "Split File",+ blurb: "Decompose an oversized module into cohesive files along its natural seams.",+ Icon: FileStack,+ accentVar: "--color-refactor-split-file",},};@@ -80,4 +86,5 @@ export const TYPE_ORDER: RefactoringType[] = ["extract_helper","move_method","break_cycle",+ "split_file",];diff --git a/packages/ui/src/refactoring/plan-before.tsx b/packages/ui/src/refactoring/plan-before.tsxindex 4d32a067f..72638abf0 100644--- a/packages/ui/src/refactoring/plan-before.tsx+++ b/packages/ui/src/refactoring/plan-before.tsx@@ -7,6 +7,8 @@ import {extractClassGroups,extractHelperOccurrences,moveTarget,+ splitGroups,+ splitResidual,type RefactoringPlan,} from "./types";@@ -154,6 +156,46 @@ export function PlanBefore({ plan }: PlanBeforeProps) {return <CycleGraph plan={plan} accent={accent} />;}+ if (plan.refactoring_type === "split_file") {+ const symbols = [...splitGroups(plan).flatMap((g) => g.symbols), ...splitResidual(plan)];+ const nloc = Number(plan.evidence?.file_nloc ?? 0);+ const count = Number(plan.evidence?.symbol_count ?? symbols.length);+ const shown = symbols.slice(0, 18);+ return (+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">+ <div className="mb-2.5 flex items-center justify-between gap-2">+ <code className="truncate text-xs font-semibold text-[var(--color-text-primary)]">+ {baseName(plan.file_path)}+ </code>+ {nloc > 0 ? (+ <span className="shrink-0 rounded-full bg-[var(--color-error)]/10 px-2 py-0.5 text-[10px] font-semibold tabular-nums text-[var(--color-error)]">+ {nloc} NLOC+ </span>+ ) : null}+ </div>+ <p className="mb-2 text-[11px] text-[var(--color-text-tertiary)]">+ {count} top-level symbol{count === 1 ? "" : "s"} in one module — loosely related, no clear+ seams.+ </p>+ <div className="flex flex-wrap gap-1">+ {shown.map((s) => (+ <code+ key={s}+ className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-tertiary)]"+ >+ {s}+ </code>+ ))}+ {symbols.length > shown.length ? (+ <span className="px-1 py-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ +{symbols.length - shown.length} more+ </span>+ ) : null}+ </div>+ </div>+ );+ }+return null;}diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsxindex 6e4b55df7..e9a04cd3c 100644--- a/packages/ui/src/refactoring/plan-detail.tsx+++ b/packages/ui/src/refactoring/plan-detail.tsx@@ -1,6 +1,6 @@"use client";-import { ArrowRight, CornerDownRight, Scissors } from "lucide-react";+import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";import { typeAccent } from "./meta";import {blastFiles,@@ -10,6 +10,10 @@ import {extractHelperOccurrences,helperSite,moveTarget,+ splitBlast,+ splitGroups,+ splitResidual,+ splitShimRequired,type RefactoringPlan,} from "./types";@@ -250,6 +254,109 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp);}+ if (plan.refactoring_type === "split_file") {+ const groups = splitGroups(plan);+ const residual = splitResidual(plan);+ const shim = splitShimRequired(plan);+ const blast = splitBlast(plan);+ const originalName = plan.file_path.split("/").pop() ?? plan.file_path;+ const shownDeps = blast.dependent_files.slice(0, 8);+ return (+ <div className="space-y-3">+ {hideIntro ? null : (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Split into {groups.length} cohesive module{groups.length === 1 ? "" : "s"} — each+ group's symbols move to a new file+ {shim ? ", with a back-compat shim left in the original path" : ""}.+ </p>+ )}+ <div className="grid gap-2.5 sm:grid-cols-2">+ {groups.map((g, i) => (+ <div+ key={i}+ className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5"+ >+ <div className="mb-1 flex items-center gap-2">+ <span+ className="h-2 w-2 rounded-full"+ style={{ backgroundColor: accent }}+ aria-hidden+ />+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">+ {g.name ?? `Group ${i + 1}`}+ </span>+ </div>+ {g.suggested_file ? (+ <div className="mb-2 flex items-center gap-1.5">+ <FilePlus2 className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ <FileRef path={g.suggested_file} fileHref={fileHref} className="min-w-0 truncate" />+ </div>+ ) : null}+ <ul className="space-y-0.5">+ {g.symbols.map((s) => (+ <li+ key={s}+ className="flex items-center gap-1.5 font-mono text-[11px] text-[var(--color-text-secondary)]"+ >+ <CornerDownRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ <span className="truncate">{s}</span>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>++ {residual.length > 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">+ <div className="mb-1.5 text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">+ Stays in {originalName} (shared core)+ </div>+ <div className="flex flex-wrap gap-1">+ {residual.map((s) => (+ <code+ key={s}+ className="rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)]"+ >+ {s}+ </code>+ ))}+ </div>+ </div>+ ) : null}++ {blast.dependent_count > 0 ? (+ <div className="space-y-1.5 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">+ <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">+ <Layers className="h-3.5 w-3.5" />+ {blast.import_rewrites > 0+ ? `Rewrite imports in ${blast.import_rewrites} dependent file${+ blast.import_rewrites === 1 ? "" : "s"+ }`+ : `${blast.dependent_count} dependent${+ blast.dependent_count === 1 ? "" : "s"+ } · same-package split, no import edits`}+ </div>+ {blast.import_rewrites > 0 ? (+ <ul className="space-y-1">+ {shownDeps.map((f) => (+ <li key={f}>+ <FileRef path={f} fileHref={fileHref} className="block truncate" />+ </li>+ ))}+ {blast.dependent_files.length > shownDeps.length ? (+ <li className="text-[11px] text-[var(--color-text-tertiary)]">+ +{blast.dependent_files.length - shownDeps.length} more+ </li>+ ) : null}+ </ul>+ ) : null}+ </div>+ ) : null}+ </div>+ );+ }+// Unknown type — show the raw blast files as a minimal fallback.const files = blastFiles(plan);return files.length ? (diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsxindex 41451ec6a..a3c028f30 100644--- a/packages/ui/src/refactoring/refactoring-board.tsx+++ b/packages/ui/src/refactoring/refactoring-board.tsx@@ -64,7 +64,7 @@ export function RefactoringBoard({fileHref,showQuadrant = true,emptyTitle = "No refactoring plans",- emptyHint = "Nothing crosses the precision bar for this repo yet. Plans appear here when a class is worth splitting, a clone worth extracting, a method worth moving, or a cycle worth cutting.",+ emptyHint = "Nothing crosses the precision bar for this repo yet. Plans appear here when a class is worth splitting, a clone worth extracting, a method worth moving, a cycle worth cutting, or a file worth decomposing.",}: RefactoringBoardProps) {const [highlighted, setHighlighted] = useState<string | null>(null);const [selected, setSelected] = useState<RefactoringPlan | null>(null);diff --git a/packages/ui/src/refactoring/refactoring-quadrant.tsx b/packages/ui/src/refactoring/refactoring-quadrant.tsxindex 1129a2874..65bcb3dec 100644--- a/packages/ui/src/refactoring/refactoring-quadrant.tsx+++ b/packages/ui/src/refactoring/refactoring-quadrant.tsx@@ -26,7 +26,16 @@ const MAX_DOTS = 120;export function RefactoringQuadrant({ plans, onSelect, height = 400 }: RefactoringQuadrantProps) {const [hovered, setHovered] = useState<RefactoringPlan | null>(null);const scored = useMemo(() => plans.filter((p) => p.rank_score > 0), [plans]);- const data = useMemo(() => scored.slice(0, MAX_DOTS), [scored]);+ // The dot budget is limited, and one high-volume type (Extract Helper / clone+ // dedup often numbers in the hundreds) must not consume it all and hide the+ // rest. Seat every other type first, in rank order, then let Extract Helper+ // fill whatever capacity remains — so Split File / Move Method / Break Cycle /+ // Extract Class always get plotted.+ const data = useMemo(() => {+ const primary = scored.filter((p) => p.refactoring_type !== "extract_helper");+ const helpers = scored.filter((p) => p.refactoring_type === "extract_helper");+ return [...primary, ...helpers].slice(0, MAX_DOTS);+ }, [scored]);const capped = scored.length > MAX_DOTS;if (data.length === 0) {@@ -69,7 +78,8 @@ export function RefactoringQuadrant({ plans, onSelect, height = 400 }: Refactori<div className="rounded-2xl border border-[var(--color-border-default)] bg-gradient-to-br from-[var(--color-bg-surface)] to-[var(--color-bg-elevated)]/30 p-2 text-[var(--color-text-primary)]">{capped ? (<p className="px-2 pt-1 text-[11px] text-[var(--color-text-tertiary)]">- Showing the top {MAX_DOTS} of {scored.length} by priority+ Plotting {data.length} of {scored.length} plans — Extract Helper yields space so every+ type stays visible</p>) : null}<div className="relative">diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.tsindex 715148498..c7f726ee0 100644--- a/packages/ui/src/refactoring/types.ts+++ b/packages/ui/src/refactoring/types.ts@@ -11,7 +11,8 @@ export type RefactoringType =| "extract_class"| "extract_helper"| "move_method"- | "break_cycle";+ | "break_cycle"+ | "split_file";export type EffortBucket = "S" | "M" | "L" | "XL";export type Confidence = "low" | "medium" | "high";@@ -133,6 +134,55 @@ export function cutEdges(plan: RefactoringPlan): CutEdge[] {});}+export interface SplitGroup {+ name: string | null;+ symbols: string[];+ suggested_file: string;+}++export function splitGroups(plan: RefactoringPlan): SplitGroup[] {+ const groups = plan.plan?.groups;+ if (!Array.isArray(groups)) return [];+ return groups.map((g) => {+ const rec = (g ?? {}) as Record<string, unknown>;+ return {+ name: typeof rec.name === "string" ? rec.name : null,+ symbols: Array.isArray(rec.symbols) ? (rec.symbols as string[]) : [],+ suggested_file: String(rec.suggested_file ?? ""),+ };+ });+}++/** The shared "core" symbols that stay in the original file (spine + leftovers).+ * Empty when the plan carries no residual group. */+export function splitResidual(plan: RefactoringPlan): string[] {+ const residual = plan.plan?.residual as Record<string, unknown> | null | undefined;+ if (!residual || typeof residual !== "object") return [];+ const symbols = residual.symbols;+ return Array.isArray(symbols) ? (symbols as string[]) : [];+}++/** Whether the original path needs a back-compat re-export shim (Python/TS/…);+ * false for same-package languages like Go where sibling files share scope. */+export function splitShimRequired(plan: RefactoringPlan): boolean {+ return (plan.plan as Record<string, unknown>)?.shim_required === true;+}++export interface SplitBlast {+ dependent_files: string[];+ dependent_count: number;+ import_rewrites: number;+}++export function splitBlast(plan: RefactoringPlan): SplitBlast {+ const br = (plan.blast_radius ?? {}) as Record<string, unknown>;+ return {+ dependent_files: Array.isArray(br.dependent_files) ? (br.dependent_files as string[]) : [],+ dependent_count: Number(br.dependent_count ?? 0),+ import_rewrites: Number(br.import_rewrites ?? 0),+ };+}+/** A one-line synopsis for the compact card — what the plan does, at a glance. */export function planSynopsis(plan: RefactoringPlan): string {switch (plan.refactoring_type) {@@ -158,6 +208,10 @@ export function planSynopsis(plan: RefactoringPlan): string {const edges = cutEdges(plan).length;return `${members} files · cut ${edges} edge${edges === 1 ? "" : "s"}`;}+ case "split_file": {+ const n = splitGroups(plan).length;+ return `Split into ${n} module${n === 1 ? "" : "s"}`;+ }default:return "";}@@ -166,13 +220,17 @@ export function planSynopsis(plan: RefactoringPlan): string {/** The files this refactoring drags along, read from whichever blast-radius* shape the type carries. */export function blastFiles(plan: RefactoringPlan): string[] {- const files = plan.blast_radius?.files;- return Array.isArray(files) ? (files as string[]) : [];+ const br = plan.blast_radius ?? {};+ for (const key of ["files", "dependent_files"] as const) {+ const v = br[key];+ if (Array.isArray(v)) return v as string[];+ }+ return [];}export function blastCount(plan: RefactoringPlan): number {const br = plan.blast_radius ?? {};- for (const key of ["file_count", "dependents_count", "callers"] as const) {+ for (const key of ["file_count", "dependents_count", "dependent_count", "callers"] as const) {const v = br[key];if (typeof v === "number" && v) return v;}@@ -196,6 +254,12 @@ export const EVIDENCE_LABELS: Record<string, string> = {cycle_size: "Cycle size",edge_count: "Edges in cycle",cut_count: "Edges to cut",+ file_nloc: "File NLOC",+ symbol_count: "Symbols",+ group_count: "Groups",+ modularity: "Modularity",+ intra_edges: "Cohesive edges",+ cut_edges: "Cut edges",};export function evidenceRows(plan: RefactoringPlan): { label: string; value: string }[] {@@ -261,9 +325,11 @@ function fmtMetric(value: unknown): string | null {}/**- * 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.+ * Read a generation self-check into a single verdict for the UI. Extract Class+ * reports an LCOM4 + TCC before/after delta; Split File reports whether the+ * generated files are below the size floor and the symbols are cleanly+ * partitioned. Any skipped/absent check — and any type without a self-check —+ * returns a neutral note rather than a false pass.*/export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null {const v = result.validation;@@ -275,6 +341,22 @@ export function generatedVerdict(result: GeneratedCode): GeneratedVerdict | null}if (status !== "checked") return null;+ if (result.refactoring_type === "split_file") {+ const improved = v.improved === true;+ const parts: string[] = [];+ const files = fmtMetric(v.file_count);+ if (files !== null) parts.push(`${files} files`);+ const maxN = fmtMetric(v.max_file_nloc);+ if (maxN !== null) parts.push(`max ${maxN} NLOC`);+ const dups = Array.isArray(v.duplicated_symbols) ? v.duplicated_symbols.length : 0;+ if (dups) parts.push(`${dups} symbol${dups === 1 ? "" : "s"} duplicated`);+ return {+ tone: improved ? "pass" : "fail",+ label: improved ? "Cleanly partitioned" : "Partition incomplete",+ ...(parts.length ? { detail: parts.join(" · ") } : {}),+ };+ }+const improved = v.improved === true;const parts: string[] = [];const beforeL = fmtMetric(v.before_lcom4);@@ -327,6 +409,25 @@ export function planWins(plan: RefactoringPlan): PlanWin[] {if (edges) wins.push({ label: `${edges} import edge${edges === 1 ? "" : "s"} cut` });break;}+ case "split_file": {+ const n = splitGroups(plan).length;+ const blast = splitBlast(plan);+ if (n) wins.push({ label: `${n} focused module${n === 1 ? "" : "s"} from one file` });+ if (blast.import_rewrites > 0) {+ wins.push({+ label: `${blast.import_rewrites} dependent file${+ blast.import_rewrites === 1 ? "" : "s"+ } to re-point`,+ });+ } else if (blast.dependent_count > 0) {+ wins.push({+ label: `${blast.dependent_count} dependent${+ blast.dependent_count === 1 ? "" : "s"+ }, zero import edits`,+ });+ }+ break;+ }}return wins;}diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.cssindex b61789677..de5b22564 100644--- a/packages/ui/styles/globals.css+++ b/packages/ui/styles/globals.css@@ -106,6 +106,17 @@--color-info: #3f6ea5; /* muted blue — distinct from the plum accent-secondary */--color-caution: #a8821f; /* between warning and success; medium severity / fair score band */+ /* Refactoring type accents — a qualitative palette (NOT semantic). Five+ well-separated hues so the types stay distinguishable as dots / rails /+ chips across the Refactoring surface. Don't fold these back into the+ amber-family semantic vars (accent-primary / caution / warning) — that is+ exactly what made extract-class / move-method / break-cycle indistinct. */+ --color-refactor-extract-class: #b9651b; /* amber */+ --color-refactor-extract-helper: #1d8155; /* green */+ --color-refactor-move-method: #6d4aa6; /* purple */+ --color-refactor-break-cycle: #b5396f; /* magenta */+ --color-refactor-split-file: #3f6ea5; /* blue */+/* Aliases — short names used in component class strings. Keep in sync. */--color-fresh: var(--color-confidence-fresh);--color-stale: var(--color-confidence-stale);@@ -333,6 +344,13 @@--color-info: #7da7d9; /* muted blue — distinct from the plum accent-secondary */--color-caution: #d9b04a;+ /* Refactoring type accents — qualitative palette (dark theme, brighter). */+ --color-refactor-extract-class: #f59520; /* amber */+ --color-refactor-extract-helper: #34d399; /* green */+ --color-refactor-move-method: #b58cf0; /* purple */+ --color-refactor-break-cycle: #ec6fa6; /* magenta */+ --color-refactor-split-file: #7da7d9; /* blue */+--color-node-undocumented: #6f6678;--viz-node-stroke: rgba(222, 210, 235, 0.22);diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsxindex 8aa01f3e1..fe4db2340 100644--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx@@ -4,7 +4,8 @@* Refactoring — `/repos/[id]/refactoring`.** A first-class surface for the deterministic refactoring plans the health- * pass writes (Extract Class, Extract Helper, Move Method, Break Cycle). The+ * pass writes (Extract Class, Extract Helper, Move Method, Break Cycle, Split+ * File). The* card board is the primary view; a priority×effort quadrant heads it. Type* filters are URL-synced via `?type=` (nuqs), mirroring the architecture view.*/diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.pyindex 530f757c1..6871c1e3f 100644--- a/tests/unit/health/test_refactoring_enrich.py+++ b/tests/unit/health/test_refactoring_enrich.py@@ -15,6 +15,7 @@ from repowise.core.analysis.health.refactoring.llm import (llm_enrichment_enabled,)from repowise.core.analysis.health.refactoring.llm.enrich import (+ _MAX_IMPORT_HEAD_LINES,_build_user_prompt,_extract_diff,_gather_spans,@@ -46,6 +47,42 @@ def _extract_class_suggestion() -> RefactoringSuggestion:)+def _split_file_suggestion() -> RefactoringSuggestion:+ return RefactoringSuggestion(+ refactoring_type="split_file",+ file_path="pkg/big.py",+ target_symbol="big.py -> 2 files",+ line_start=None,+ line_end=None,+ plan={+ "groups": [+ {+ "name": "parsing",+ "symbols": ["parse_a", "parse_b"],+ "suggested_file": "pkg/parsing.py",+ },+ {+ "name": "rendering",+ "symbols": ["render_a", "render_b"],+ "suggested_file": "pkg/rendering.py",+ },+ ],+ "residual": {"symbols": ["shared_helper"]},+ "shim_required": True,+ },+ evidence={"file_nloc": 400, "symbol_count": 8, "group_count": 2, "modularity": 0.5},+ impact_delta=0.0,+ effort_bucket="L",+ blast_radius={+ "dependent_files": ["pkg/user.py"],+ "dependent_count": 1,+ "import_rewrites": 1,+ },+ confidence="high",+ source_biomarker="",+ )++def _write_source(repo: Path, rel: str, body: str) -> None:path = repo / relpath.parent.mkdir(parents=True, exist_ok=True)@@ -95,6 +132,26 @@ def test_gather_spans_extract_helper_reads_every_occurrence(tmp_path: Path) -> Nassert files == {"pkg/a.py", "pkg/b.py"}+def test_gather_spans_split_file_reads_whole_module_and_dependent_heads(tmp_path: Path) -> None:+ _write_source(tmp_path, "pkg/big.py", "\n".join(f"line{i} = {i}" for i in range(1, 401)))+ _write_source(tmp_path, "pkg/user.py", "\n".join(f"u{i}" for i in range(1, 100)))+ spans = _gather_spans(_split_file_suggestion(), tmp_path)+ by_file = {s.file: s for s in spans}+ assert set(by_file) == {"pkg/big.py", "pkg/user.py"}+ # The whole module is read — well past the 240-line default span cap.+ assert by_file["pkg/big.py"].end_line == 400+ # The dependent contributes only its import header.+ assert by_file["pkg/user.py"].end_line <= _MAX_IMPORT_HEAD_LINES+++def test_user_prompt_split_file_carries_instruction_and_groups(tmp_path: Path) -> None:+ _write_source(tmp_path, "pkg/big.py", "def parse_a():\n return 1\n")+ spans = _gather_spans(_split_file_suggestion(), tmp_path)+ prompt = _build_user_prompt(_split_file_suggestion(), spans)+ assert "SPLIT FILE" in prompt+ assert "parsing" in prompt and "pkg/parsing.py" in prompt++def test_gather_spans_skips_path_escape(tmp_path: Path) -> None:sug = _extract_class_suggestion()sug.file_path = "../outside.py"@@ -213,6 +270,90 @@ async def test_self_check_skipped_when_no_code_blocks(tmp_path: Path) -> None:assert result.validation["status"] == "skipped"+# ---------------------------------------------------------------------------+# Size + partition self-check (Split File)+# ---------------------------------------------------------------------------+++_TWO_PARTITIONED_FILES = """\+Split done.++```python+def parse_a():+ return 1+++def parse_b():+ return 2+```++```python+def render_a():+ return 3+++def render_b():+ return 4+```+"""+++_DUPLICATED_FILES = """\+```python+def parse_a():+ return 1+```++```python+def parse_a():+ return 1+++def render_a():+ return 3+```+"""+++async def test_split_file_self_check_reports_clean_partition(tmp_path: Path) -> None:+ _write_source(tmp_path, "pkg/big.py", "def parse_a():\n return 1\n" + "x = 1\n" * 400)+ provider = MockProvider(responses=[GeneratedResponse(_TWO_PARTITIONED_FILES, 10, 50)])+ result = await enrich_suggestion(+ _split_file_suggestion(), provider=provider, repo_path=tmp_path+ )+ v = result.validation+ assert v["status"] == "checked"+ assert v["file_count"] == 2+ assert v["partitioned"] is True+ assert v["duplicated_symbols"] == []+ assert v["all_below_floor"] is True+ assert v["improved"] is True+++async def test_split_file_self_check_flags_duplicated_symbol(tmp_path: Path) -> None:+ _write_source(tmp_path, "pkg/big.py", "def parse_a():\n return 1\n")+ provider = MockProvider(responses=[GeneratedResponse(_DUPLICATED_FILES, 10, 50)])+ result = await enrich_suggestion(+ _split_file_suggestion(), provider=provider, repo_path=tmp_path+ )+ v = result.validation+ assert v["status"] == "checked"+ assert "parse_a" in v["duplicated_symbols"]+ assert v["partitioned"] is False+ assert v["improved"] is False+++async def test_split_file_self_check_skipped_for_single_block(tmp_path: Path) -> None:+ _write_source(tmp_path, "pkg/big.py", "def parse_a():\n return 1\n")+ provider = MockProvider(+ responses=[GeneratedResponse("```python\ndef parse_a():\n return 1\n```", 5, 5)]+ )+ result = await enrich_suggestion(+ _split_file_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(