Intelligently scan and refactor large code files into smaller, maintainable action-pattern based components following language and framework conventions

Install

/plugin install code-splitter@own-plugins-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add MaxBoiko21/claude-plugins-marketplace.

Contents

Discovered from source

Skills 2

Action Pattern Conventions

Purpose

This skill provides language and framework-specific guidance for implementing the action pattern across different technology stacks. It explains conventions for creating focused, reusable action classes, components, services, and modules that encapsulate specific business operations.

When to Use

Use this skill when refactoring code into actions, understanding how to structure operations for a specific framework, or ensuring extracted code follows project conventions. It covers Laravel, Symfony, React, Vue, and Node.js.

Universal Action Pattern

The action pattern applies universally across frameworks:

Core concept: One action = one operation with a clear entry point

Characteristics:

  • Single responsibility: One reason to exist
  • Clear interface: Single entry method (handle(), execute(), call method)
  • Dependency injection: Dependencies injected, not global
  • Reusability: Can be called from multiple contexts (controllers, jobs, CLI, API, webhooks)
  • Testability: Testable in isolation
  • Naming: Describes the operation clearly

Pattern:

public function handle($input) {
    // 1. Validate/prepare input
    // 2. Execute operation (business logic)
    // 3. Return result or side effect
}

Laravel Action Pattern

File Structure

app/
├── Actions/
│   ├── Users/
│   │   ├── CreateUserAction.php
│   │   ├── UpdateUserAction.php
│   │   └── DeleteUserAction.php
│   ├── Orders/
│   │   ├── CreateOrderAction.php
│   │   └── ProcessPaymentAction.php
│   └── Notifications/
│       ├── SendWelcomeEmailAction.php
│       └── SendOrderConfirmationAction.php

Basic Action Class

<?php

namespace App\Actions\Users;

final readonly class CreateUserAction {
    public function __construct(private UserRepository $users) {}

    public function handle(array $data): User {
        // Validate (optional, can use Form Request instead)
        $validated = $this->validate($data);

        // Create user
        $user = $this->users->create($validated);

        // Side effects (notifications, etc.)
        // Only if tightly coupled to creation
        // Otherwise use jobs or separate actions

        return $user;
    }

    private function validate(array $data): array {
        // Custom validation if needed
        return $data;
    }
}

Usage in Controllers

class UserController extends Controller {
    public function store(CreateUserRequest $request, CreateUserAction $createUser) {
        // Constructor injection of action
        $user = $createUser->handle($request->validated());

        return response()->json(['user' => $user], 201);
    }
}

Naming Conventions

Action class names:

  • Operation + "Action" suffix: CreateUserAction, SendEmailAction
  • Verb-noun format: Clear what it does
  • Namespace by domain: Users/, Orders/, Payments/

Method names:

  • handle() - Primary method for the action
  • Specific methods for complex operations: validateUser(), persistToDatabase()

File structure:

  • One action per file
  • Directory per domain/entity type
  • app/Actions/ root directory

Advanced Patterns

Action with Transaction:

final readonly class CreateOrderAction {
    public function __construct(private OrderRepository $orders) {}

    public function handle(array $data): Order {
        return DB::transaction(function () use ($data) {
            $order = $this->orders->create($data);
            $this->orders->attachItems($order->id, $data['items']);
            return $order;
        });
    }
}

Action with Events:

final readonly class ProcessPaymentAction {
    public function __construct(private PaymentGateway $gateway) {}

    public function handle(Order $order): Payment {
        $payment = $this->gateway->process($order->total);

        // Dispatch event instead of tightly coupling logic
        event(new PaymentProcessed($order, $payment));

        return $payment;
    }
}

Action Composition:

final readonly class CompleteOrderAction {
    public function __construct(
        private ProcessPaymentAction $processPayment,
        private SendConfirmationAction $sendConfirmation,
    ) {}

    public function handle(Order $order): Order {
        $payment = $this->processPayment->handle($order);
        $this->sendConfirmation->handle($order);

        return $order->markComplete();
    }
}

React Component & Hook Pattern

Component Structure

src/
├── components/          # Reusable UI components
│   ├── button.tsx
│   ├── card.tsx
│   └── form-field.tsx
├── sections/            # Composite sections (headers, forms, features)
│   ├── user-profile-form.tsx
│   └── order-summary.tsx
├── layouts/             # Page layouts
│   ├── dashboard-layout.tsx
│   └── auth-layout.tsx
└── pages/               # Route pages
    ├── users/
    │   ├── index.tsx
    │   └── show.tsx
    └── orders/
        ├── index.tsx
        └── create.tsx

Component Convention

Small, focused components (<100 lines):

interface ButtonProps {
    label: string;
    onClick: () => void;
    variant?: 'primary' | 'secondary';
}

export function Button({ label, onClick, variant = 'primary' }: ButtonProps) {
    return (
        <button
            className={`btn btn-${variant}`}
            onClick={onClick}
        >
            {label}
        </button>
    );
}

Composite sections (reusable blocks):

interface UserFormProps {
    user?: User;
    onSubmit: (data: UserData) => Promise<void>;
}

export function UserProfileForm({ user, onSubmit }: UserFormProps) {
    const form = useUserForm(user);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        await onSubmit(form.data);
    };

    return (
        <form onSubmit={handleSubmit}>
            <FormField label="Name" value={form.data.name} />
            <FormField label="Email" value={form.data.email} />
            <button type="submit">Save</button>
        </form>
    );
}

Custom Hook Convention

Naming:

  • use + PascalCase: useUserForm, useFetchUsers, useAuthContext
  • Describe what it does: useFormValidation, useLocalStorage, usePaginatedData

Pattern:

function useUserForm(initialUser?: User) {
    const [data, setData] = useState(initialUser || {});
    const [errors, setErrors] = useState({});

    const validate = () => {
        // Validation logic
    };

    const submit = async () => {
        // Submit logic
    };

    return { data, setData, errors, validate, submit };
}

// Usage
function MyComponent() {
    const form = useUserForm(user);
    return <form onSubmit={form.submit}>...</form>;
}

Composition Pattern

Extract child components:

function UserDashboard({ userId }) {
    const user = useUserData(userId);

    return (
        <div className="dashboard">
            <UserHeader user={user} />
            <UserStats user={user} />
            <UserActivity user={user} />
        </div>
    );
}

// Separate components
function UserHeader({ user }) {
    return <header>{user.name}</header>;
}

function UserStats({ user }) {
    return <div>Stats content</div>;
}

function UserActivity({ user }) {
    return <div>Activity content</div>;
}

Vue Composition & Pattern

Component Structure

src/
├── components/          # Reusable UI components
├── views/              # Route views/pages
├── composables/        # Reusable composition functions
│   ├── useUserForm.ts
│   └── useFetchData.ts
└── services/           # API client services
    └── userService.ts

Composable Convention

// composables/useUserForm.ts
import { ref, computed } from 'vue';

export function useUserForm(initialUser = null) {
    const data = ref(initialUser || {});
    const errors = ref({});

    const validate = () => {
        // Validation logic
    };

    const submit = async () => {
        // Submit logic
    };

    return { data, errors, validate, submit };
}

// Usage in component
<script setup lang="ts">
import { useUserForm } from '@/composables/useUserForm';

const form = useUserForm(props.user);
</script>

Node.js / TypeScript Pattern

Service Structure

src/
├── services/
│   ├── user.service.ts
│   ├── order.service.ts
│   ├── email.service.ts
│   └── payment.service.ts
├── repositories/       # Data access
│   ├── user.repository.ts
│   └── order.repository.ts
├── actions/           # Complex operations
│   ├── create-order.action.ts
│   └── process-payment.action.ts
└── utils/             # Helper functions
    ├── validation.ts
    └── formatting.ts

Service Class Convention

export class UserService {
    constructor(private userRepository: UserRepository) {}

    async create(data: CreateUserDTO): Promise<User> {
        // Operation logic
        return user;
    }

    async update(id: string, data: UpdateUserDTO): Promise<User> {
        // Operation logic
        return user;
    }

    async delete(id: string): Promise<void> {
        // Operation logic
    }
}

Action Class Convention (Node.js)

export class CreateOrderAction {
    constructor(
        private orderService: OrderService,
        private paymentService: PaymentService,
    ) {}

    async execute(data: CreateOrderDTO): Promise<Order> {
        // Complex multi-step operation
        const order = await this.orderService.create(data);

        if (data.paymentMethod) {
            await this.paymentService.process(order.id, data.paymentMethod);
        }

        return order;
    }
}

Helper Function Convention

// utils/validation.ts
export function validateEmail(email: string): boolean {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export function validatePassword(password: string): boolean {
    return password.length >= 8;
}

// Usage
if (!validateEmail(email)) {
    throw new Error('Invalid email');
}

Framework Auto-Detection

The plugin auto-detects your project type based on:

Laravel:

  • Presence of composer.json with laravel/framework
  • Directory structure with app/, routes/, config/

React:

  • Presence of package.json with react dependency
  • .tsx or .jsx files in src/

Vue:

  • Presence of package.json with vue dependency
  • .vue files in src/

Node.js / Symfony:

  • Presence of package.json or composer.json
  • Service-based file structure

Customization per Project

Override defaults in .claude/code-splitter.local.md:

---
# Laravel
laravel_actions_path: app/Actions
laravel_action_namespace: "App\\Actions"

# React
react_components_path: src/components
react_hooks_path: src/hooks

# Vue
vue_composables_path: src/composables
vue_components_path: src/components

# Node.js
node_services_path: src/services
node_actions_path: src/actions

# General
action_method_name: execute      # Instead of handle
max_lines_per_file: 100
---

Additional Resources

For detailed examples and advanced patterns, see:

  • references/framework-patterns.md - Comprehensive framework-specific patterns
  • examples/ - Real working examples for each framework

Key Principles

  1. One operation per action/service: Clear, focused responsibility
  2. Dependency injection: Inject dependencies, don't rely on globals
  3. Reusability: Can be called from multiple contexts
  4. Testability: Testable in isolation with mocked dependencies
  5. Naming clarity: Names describe what the action does
  6. Framework conventions: Follow established patterns for your framework

Next steps: Use /scan-code to identify refactoring candidates, or /split-code <file> to apply these patterns to your code.

Code Refactoring Patterns

Purpose

This skill provides guidance on refactoring large, complex code files into smaller, focused, and maintainable components. It covers fundamental refactoring principles, extraction strategies, and patterns that apply across programming languages and frameworks.

When to Use

Use this skill when analyzing code structure, planning refactoring strategies, or deciding how to split large files. It provides language-agnostic principles that work whether refactoring Laravel controllers, React components, Node.js services, or any codebase.

Core Refactoring Principles

1. Single Responsibility Principle (SRP)

Each function, class, or module should have one reason to change. Identify when code violates SRP:

  • Controllers handling validation, business logic, and response formatting → Extract validation and business logic to separate classes
  • Components managing state, data fetching, and rendering → Extract hooks and services
  • Service classes with 15+ public methods → Break into focused services
  • Functions doing multiple operations → Extract each operation to its own function

Question to ask: "If this code needs to change, how many different reasons could require that change?" More than one reason signals SRP violation.

2. Extractable Boundaries

Identify clear extraction boundaries by looking for:

  • Distinct workflows: Methods performing completely different operations (e.g., user creation separate from email sending)
  • Reusable logic: Code that appears in multiple places or could be used elsewhere
  • High complexity: Methods exceeding 15-20 lines or with nested conditionals
  • Clear input/output: Methods with well-defined inputs and outputs (easier to extract)
  • Testability: Logic that would benefit from independent testing

Extraction pattern:

1. Identify the boundary (start/end of related operations)
2. Extract to new method/function
3. Verify no side effects or tight coupling
4. Test independently
5. Update references

3. Complexity Metrics

Recognize complexity that signals refactoring need:

  • Cyclomatic Complexity > 10: Multiple branches, nested conditions → Extract conditional logic to separate methods
  • Method length > 20 lines: Likely handling multiple concerns → Break into smaller methods
  • Nesting depth > 3 levels: Hard to follow logic → Extract inner logic to separate methods
  • Parameter count > 4: Hard to understand and test → Group parameters into objects
  • Method with many local variables: Suggests multiple concerns → Extract to separate methods

4. Naming and Intent

After extraction, ensure clear naming:

  • Method names should describe intent: validateUserEmail() not check(), processPayment() not do()
  • Extract Guard Clauses: Early returns for edge cases make the happy path clear
  • Extract Error Handling: Separate validation from business logic
  • Extract Loops: Extract loop bodies to named methods that describe the operation

Example:

// Before: Hard to understand at a glance
public function createUser($data) {
    if (!$data['email']) return false;
    if (User::where('email', $data['email'])->exists()) return false;
    // ... 30 more lines
}

// After: Clear intent with extracted boundaries
public function createUser($data) {
    if (!$this->validateUserData($data)) return false;
    if ($this->userExists($data['email'])) return false;
    return $this->storeUser($data);
}

Extraction Patterns by Language

PHP / Laravel

Extract CRUD operations into Action classes:

  • CreateUserAction - Only handles creation logic
  • UpdateUserAction - Only handles updates
  • DeleteUserAction - Only handles deletion
  • GetUserAction - Only handles retrieval with related data

Extract validation into separate methods or Form Requests:

  • ValidateUserInput method or Form Request class
  • Keep business logic separate from validation

Extract queries into scopes and methods:

  • scopeActive() → User::query()->active()
  • scopeByEmail() → User::query()->byEmail($email)

Extract relationships into dedicated classes:

  • Models with complex relationships → Separate trait files
  • Resource formatting → Dedicated Resource class

React / Vue

Extract large components into smaller pieces:

  • Container components (data management) separate from presentational components (rendering)
  • Extract hooks for reusable logic
  • Extract smaller, focused sub-components

Extract hooks for reusable logic:

  • useUserPermissions() → Encapsulates permission checking
  • useFormValidation() → Handles form state and validation
  • useDataFetching() → Wraps React Query or SWR

Extract context providers:

  • Theme context separate from Auth context
  • Each context for one concern

Node.js / TypeScript

Extract service methods into focused services:

  • UserService → User-specific operations
  • EmailService → Email operations
  • PaymentService → Payment operations

Extract helper/utility functions:

  • validateEmail(), hashPassword(), formatResponse()
  • Keep pure functions in separate files

Extract data access patterns:

  • Database queries → Repository pattern or separate data access file
  • API calls → Separate API client file

Refactoring Workflow

Step 1: Analyze Current Code

Read the file and identify:

  • Current responsibilities (what does this code do?)
  • Violation areas (where are multiple concerns mixed?)
  • Extraction candidates (which parts could be separate?)
  • Dependencies (what does extracted code depend on?)

Step 2: Design Target Structure

Plan the refactoring:

  • How many files/classes should be created?
  • What will each contain?
  • How will they interact?
  • What's the folder structure?

Step 3: Extract with Care

  • Extract one concern at a time
  • Update references to extracted code
  • Verify functionality still works
  • Run tests (if available)

Step 4: Validate

  • Does each extracted component have single responsibility?
  • Are dependencies clear and minimal?
  • Is the code easier to understand and test?
  • Can extracted code be reused elsewhere?

Common Extraction Scenarios

Scenario 1: Large Controller Class

Problem: 50+ line controller method doing validation, business logic, and response formatting

Solution:

  1. Extract validation to Form Request or validator method
  2. Extract business logic to Action class
  3. Keep controller thin (3-5 lines)

Scenario 2: Complex Component

Problem: React component with 200+ lines doing data fetching, state management, and rendering

Solution:

  1. Extract data fetching to custom hook
  2. Extract child components for different sections
  3. Extract form logic to separate hook
  4. Component becomes 30-40 lines focused on layout

Scenario 3: God Service Class

Problem: Service class with 30+ public methods handling multiple unrelated operations

Solution:

  1. Group related methods into separate service classes
  2. Service A: UserCreation operations
  3. Service B: UserNotification operations
  4. Service C: UserPermissions operations
  5. Update references to use appropriate service

Scenario 4: Conditional Logic

Problem: Method with 5+ nested if/else levels

Solution:

  1. Extract guard clauses to top (early returns)
  2. Extract condition checking to named methods
  3. Extract branch logic to separate methods
  4. Result: Clear happy path with early exits

Patterns to Follow

Action Pattern (Preferred for Business Logic)

Characteristics:

  • Single handle() method with clear purpose
  • Dependencies injected via constructor
  • Reusable from commands, controllers, jobs, API requests
  • Easy to test

When to use: Any complex business logic (user creation, payment processing, data transformation)

Hook Pattern (React/Vue)

Characteristics:

  • Reusable logic encapsulated
  • Composed into components
  • Separate concerns (state, effects, validation)
  • Testable independently

When to use: Reusable component logic (form handling, data fetching, permissions)

Service Pattern (Node.js/Backend)

Characteristics:

  • Focused on specific domain
  • Clear public interface
  • Encapsulates related operations
  • Stateless or minimal state

When to use: Domain-specific operations (UserService, EmailService, PaymentService)

Red Flags for Refactoring Need

Extract code when you see:

  • DRY Violation: Same code appears 2+ times → Extract to reusable function
  • Naming Confusion: Can't describe what a method does in a sentence → Doing too much
  • Test Difficulty: Hard to test a method in isolation → Likely mixed concerns
  • Multiple Reasons to Change: Modification requests affect different parts of code → SRP violation
  • Deep Nesting: More than 3 levels of indentation → Extract inner logic
  • Long Parameter Lists: More than 4 parameters → Group into object/DTO
  • Many Local Variables: More than 5-6 variables → Likely multiple concerns
  • Scroll Fatigue: Method longer than screen height → Break into smaller methods

Advanced Patterns

Refactoring with Dependencies

When extracting code with external dependencies:

  1. Identify which services/dependencies are needed
  2. Pass them as constructor parameters or method arguments
  3. Extracted code is testable with mocked dependencies
  4. Original code still works, now calling extracted code

Refactoring with State

When extracting code that manages state:

  1. Move state and state-changing logic together
  2. Use appropriate state management (Context in React, local in Vue, closures in JS)
  3. Ensure clear ownership of state
  4. Extracted code has clear input/output

Refactoring with Side Effects

When extracting code with side effects (DB writes, API calls, file I/O):

  1. Extract the effect operation to separate method
  2. Keep business logic pure when possible
  3. Side effects at boundaries (entry points)
  4. Easier to test pure logic separately

Additional Resources

For language and framework-specific action patterns, see:

  • references/extraction-patterns.md - Detailed extraction techniques
  • references/smell-indicators.md - Code smell checklist
  • examples/ - Working refactoring examples

Next Steps

After understanding refactoring principles, use the /scan-code command to identify candidates in your codebase, or /split-code <file> to refactor specific files following these patterns.

Commands 2

Scan Codebase for Refactoring Candidates

Analyze the entire project to identify files needing refactoring based on:

  • Size: Files exceeding line count thresholds
  • Complexity: Methods/functions exceeding function count or cyclomatic complexity
  • Patterns: Files not following action pattern conventions

How It Works

  1. Scan the project: Use Glob to identify all relevant code files
  2. Analyze each file: Check size, method/function count, and patterns
  3. Generate report: Present findings in interactive format with metrics
  4. Present candidates: User can select which files to refactor with /split-code

Instructions for Claude

Read project configuration from .claude/code-splitter.local.md if it exists (use Read tool).

Default thresholds (can be overridden in project config):

  • Size threshold: 300 lines of code
  • Method/function threshold: 10 methods/functions per file
  • Frameworks to detect: Laravel, Symfony, React, Vue, Node.js

Step 1: Detect Project Type

Use package.json, composer.json, and file structure to determine:

  • Is this a Laravel/Symfony project? (check composer.json, app/ directory)
  • Is this a React/Vue project? (check package.json, src/ directory)
  • Is this a Node.js backend? (check package.json structure)
  • Is this a mixed project? (multiple frameworks)

Step 2: Identify Files to Scan

Based on project type, identify relevant file patterns:

Laravel/Symfony:

  • Controllers: app/**/*Controller.php, src/**/Controller/
  • Services: app/**/Service.php, src/**/Service/
  • Models: app/**/*.php excluding Controllers, Actions
  • Any file >300 lines in app/ or src/

React/Vue:

  • Components: src/components/**/*.{jsx,tsx,vue}
  • Sections: src/sections/**/*.{jsx,tsx,vue}
  • Pages: src/pages/**/*.{jsx,tsx,vue}
  • Hooks/Composables: src/hooks/**/*.ts, src/composables/**/*.ts

Node.js:

  • Services: src/services/**/*.ts
  • Controllers/Handlers: src/routes/**/*.ts, src/handlers/**/*.ts
  • Any file >300 lines in src/

Step 3: Analyze Each File

For each file:

  1. Count lines: Total lines of code (excluding comments/blanks for accuracy)

  2. Count methods/functions:

    • PHP: Count public function, private function, protected function
    • JS/TS: Count function, async function, const x = () => {}
    • Vue/React: Count function, exports, methods
  3. Assess pattern violations:

    • Controllers with business logic (>30 lines of non-routing logic)
    • Large components without child components
    • Services doing multiple unrelated things
    • Files not following action pattern conventions
  4. Calculate refactoring score:

    • Size violation: lines > 300 → add 1 point
    • Complexity violation: methods > 10 → add 1 point
    • Pattern violation: detected → add 1 point
    • Score > 0 = refactoring candidate

Step 4: Generate Interactive Report

Present results as an interactive selection menu:

📊 Code Splitter Scan Report
=============================

Project Type: Laravel
Files Analyzed: 42
Candidates Found: 7

Refactoring Candidates:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

□ app/Http/Controllers/UserController.php
  Lines: 425 | Methods: 15 | Score: 2/3
  Issues: Size violation (125 lines over), complexity violation (5 extra methods)

□ app/Services/OrderService.php
  Lines: 380 | Methods: 18 | Score: 2/3
  Issues: Too many methods, mixed concerns (creation, payment, shipping)

□ app/Models/User.php
  Lines: 220 | Methods: 12 | Score: 1/3
  Issues: Complexity violation (2 extra methods)

✓ All other files are within thresholds

Recommended Action:
Use `/split-code <file-path>` on any candidate above to refactor it.

Step 5: Interactive Selection (Optional)

If user wants, present a checkbox interface to select multiple candidates:

Select files to analyze further:

[✓] app/Http/Controllers/UserController.php
[ ] app/Services/OrderService.php
[ ] app/Models/User.php

Press to analyze selected files

Output Format

Present as:

  1. Summary: Total files analyzed, candidates found
  2. Detailed list: Each candidate with metrics
  3. Recommendations: Which files to prioritize
  4. Next steps: Tell user to run /split-code <file-path> to refactor

Error Handling

  • If project has no code files: "No code files found. Verify project structure."
  • If config file is malformed: Use default thresholds with warning
  • If file is binary: Skip (don't try to read)

Tips

  • Sort candidates by refactoring score (highest first)
  • Group by file type for easier processing
  • Show framework-specific violation info (e.g., "Controller with business logic" for Laravel)
  • Only show files that are actually refactoring candidates (have violations)

Example Output Formats

Laravel Project:

File: app/Http/Controllers/UserController.php
Type: Controller
Lines: 425 (threshold: 300, 125 over)
Methods: 15 (threshold: 10, 5 over)
Violations:
  • Size: 425 lines exceeds 300 line threshold
  • Complexity: 15 methods exceeds 10 method threshold
  • Pattern: Heavy business logic should be in Action classes
Score: 3/3 - High Priority

React Project:

File: src/components/Dashboard.tsx
Type: Component
Lines: 380 (threshold: 300, 80 over)
Methods: 8 hooks + embedded logic
Violations:
  • Size: 380 lines exceeds 300 line threshold
  • Logic: Data fetching, form state, and rendering mixed
  • Pattern: Should split into sub-components and custom hooks
Score: 2/3 - Medium Priority

Configuration

Read .claude/code-splitter.local.md for overrides:

  • line_threshold: Override 300 line default
  • method_threshold: Override 10 method default
  • Language-specific paths to scan

Refactor and Split Specific File

Analyze a specific file and execute refactoring to split it into smaller, focused components following action pattern conventions.

Parameters

  • file-path (required): Full path to the file to refactor

How It Works

  1. Analyze the file: Read and understand its structure, responsibilities, and violations
  2. Propose refactoring plan: Show which code will be extracted and where
  3. User approval: User selects which extractions to perform
  4. Execute refactoring: Create new files and update imports
  5. Validate: Check syntax and suggest improvements

Instructions for Claude

Step 1: Read and Analyze the File

  1. Use Read tool to load the specified file
  2. Understand its current structure:
    • What is it doing? (business logic, data access, rendering, etc.)
    • How many methods/functions? What do they do?
    • How many lines?
    • Current violations (size, complexity, multiple concerns)
  3. Determine the file type:
    • PHP file? (Laravel controller, service, model)
    • JavaScript/TypeScript? (Node service, React component, Vue component)
    • Identify the framework context

Step 2: Load Project Configuration

  1. Try to read .claude/code-splitter.local.md from project root
  2. Extract project preferences:
    • Target action paths (laravel_actions_path, react_components_path, etc.)
    • Language-specific conventions
    • Naming preferences
  3. If no config exists, use defaults for detected framework

Step 3: Propose Refactoring Plan

Create a detailed plan showing:

For each extraction:

  • What code is being extracted (which methods/functions/sections)
  • Where it will be created (new file path following conventions)
  • What dependencies it needs
  • How it connects to remaining code

Example Laravel plan:

Refactoring Plan: app/Http/Controllers/UserController.php
═════════════════════════════════════════════════════════

Current Issues:
  • File size: 425 lines (125 lines over threshold)
  • Methods: 15 (5 methods over threshold)
  • Mixed concerns: routing, validation, business logic, email sending

Proposed Extractions:

1. Create User Action
   File: app/Actions/Users/CreateUserAction.php
   Extracts: store() method business logic
   Dependencies: User model, Mail service
   Connections: Controller calls this action

2. Update User Action
   File: app/Actions/Users/UpdateUserAction.php
   Extracts: update() method business logic
   Dependencies: User model
   Connections: Controller calls this action

3. Delete User Action
   File: app/Actions/Users/DeleteUserAction.php
   Extracts: destroy() method logic
   Dependencies: User model
   Connections: Controller calls this action

4. Send User Invitation
   File: app/Actions/Users/SendUserInvitationAction.php
   Extracts: sendInvitation() method
   Dependencies: Mail service
   Connections: Controller calls this action

Result:
  • Controller reduced to ~50 lines (routing only)
  • Each action has single responsibility
  • Code is testable and reusable
  • Following Laravel action pattern

For React/Vue, show component breakdown:

Refactoring Plan: src/components/UserDashboard.tsx
═════════════════════════════════════════════════

Current Issues:
  • Component size: 380 lines (80 over threshold)
  • Mixed concerns: data fetching, form state, rendering
  • No child components

Proposed Extractions:

1. useUserData Hook
   File: src/hooks/useUserData.ts
   Extracts: User fetching logic
   Dependencies: React Query/SWR
   Connections: UserDashboard imports and uses it

2. UserProfile Component
   File: src/sections/UserProfile.tsx
   Extracts: Profile rendering section
   Dependencies: User type
   Connections: Receives user prop from UserDashboard

3. UserForm Component
   File: src/sections/UserForm.tsx
   Extracts: Form rendering and submission
   Dependencies: useUserForm hook
   Connections: Receives user prop, calls onSuccess

4. UserActivity Component
   File: src/sections/UserActivity.tsx
   Extracts: Activity list rendering
   Dependencies: useUserActivities hook
   Connections: Receives userId prop

Result:
  • Dashboard component: ~50 lines of layout
  • Each section has single responsibility
  • Reusable hooks and components
  • Better code organization

Step 4: Present Plan to User

Format as structured proposal:

  • Show current issues clearly
  • List each extraction with file path and purpose
  • Show resulting file structure
  • Ask user: "Should I proceed with this plan?" or "Would you like to adjust?"

Step 5: User Selection

Allow user to:

  • Accept the entire plan
  • Remove specific extractions ("Don't extract #3")
  • Add notes or adjustments
  • Proceed to execution

Step 6: Execute Refactoring

For each extraction the user approved:

  1. Create new file:

    • Use Write tool to create new file at proposed location
    • Copy extracted code into new file
    • Add necessary imports/dependencies
    • Add proper file structure (class, function, component, etc.)
  2. Update original file:

    • Use Edit tool to replace extracted code with function/class call
    • Add imports for new files
    • Keep only the router/handler/layout logic
  3. Validate syntax:

    • Check if file is valid (no syntax errors)
    • Verify imports are correct
    • Ensure function signatures match

Step 7: Generate Summary & Suggestions

Show user what was created:

✅ Refactoring Complete!
═════════════════════════════════════════

Files Created:
  ✓ app/Actions/Users/CreateUserAction.php (45 lines)
  ✓ app/Actions/Users/UpdateUserAction.php (38 lines)
  ✓ app/Actions/Users/DeleteUserAction.php (25 lines)

Files Modified:
  ✓ app/Http/Controllers/UserController.php
    Reduced from 425 → 65 lines

Result:
  • Original controller now focused on routing only
  • Each action has clear single responsibility
  • Code is testable and reusable from multiple places
  • Following Laravel action pattern

Next Steps:
  1. Run tests to verify functionality
  2. Check imports if using IDE
  3. Consider creating test files for new actions

Step 8: Validation & Suggestions

After refactoring, suggest improvements:

💡 Suggestions for Further Improvement:

1. Create Factory for CreateUserAction tests
   Path: database/factories/UserFactory.php

2. Consider extracting validation to Form Request
   Path: app/Http/Requests/StoreUserRequest.php

3. Add event dispatching for user creation
   Would allow notifications without tight coupling

Language-Specific Handling

Laravel/Symfony

  • Extract to Action classes in app/Actions/ (Laravel) or src/Service/ (Symfony)
  • Each action: handle() or execute() method
  • Dependency injection via constructor
  • Use Form Requests for validation
  • Auto-generate factories if project uses them

React

  • Extract to custom hooks (state/logic) in src/hooks/
  • Extract to components (rendering) in src/components/ or src/sections/
  • Use TypeScript interfaces for props
  • Custom hooks start with use prefix
  • Memoize if needed

Vue

  • Extract to composables (logic) in src/composables/
  • Extract to components (rendering) in src/components/ or src/views/
  • Use TypeScript interfaces
  • Composables start with use prefix
  • Return reactive objects

Node.js

  • Extract to Service classes in src/services/
  • Extract to Action classes for complex multi-step operations
  • Dependency injection via constructor
  • Use TypeScript for type safety

File Handling

Before Creating Files:

  1. Check if target directory exists (using Glob)
  2. Check if file already exists
  3. If exists, ask user: "File exists, should I overwrite?"

Import Updates:

  1. Auto-add necessary imports to modified files
  2. Update references from old methods to new extracted classes/functions
  3. Verify import paths are correct for the project structure

Error Handling

  • Invalid file path: "File not found. Check the path and try again."
  • Unrecognized file type: "Cannot refactor this file type. Supported: .php, .tsx, .ts, .vue, .jsx"
  • Parse error: "Could not parse file. Check for syntax errors first."
  • Permission denied: "Cannot write to target directory. Check permissions."

Tips for Quality Results

  • Preserve comments and documentation
  • Keep cohesive logic together
  • Don't create too many tiny files (each should be ~30-100 lines)
  • Group related actions together (all User actions in Users/ folder)
  • Update tests if they exist
  • Suggest adding test files for new actions/components

Configuration

Read .claude/code-splitter.local.md:

  • laravel_actions_path: Where to create Laravel actions
  • react_components_path: Where to create React components
  • vue_composables_path: Where to create Vue composables
  • node_services_path: Where to create Node services
  • Any language-specific conventions

Agents 1

Code Splitter Agent

You are an expert code refactoring agent specializing in splitting large, complex code files into smaller, focused, maintainable components following action pattern conventions.

Your Core Responsibilities

  1. Analyze code structure: Understand file size, complexity, method/function count, and responsibility distribution
  2. Identify extraction opportunities: Recognize which code should be extracted into separate files/components
  3. Propose refactoring plans: Create detailed, user-friendly proposals showing what will be extracted where
  4. Respect project conventions: Follow project-specific action patterns, folder structures, and naming conventions
  5. Execute refactoring safely: Create new files, update imports, validate syntax without breaking functionality
  6. Validate quality: Ensure generated code follows best practices and is testable

Analysis Process

Phase 1: Project Context & Configuration

  1. Detect project type from file structure, dependencies, and file extensions:

    • Laravel: composer.json with laravel/framework, app/ directory structure
    • React: package.json with react, src/ with .tsx/.jsx files
    • Vue: package.json with vue, src/ with .vue files
    • Node.js/Symfony: Service-based structure
    • Mixed projects: Multiple frameworks
  2. Read .claude/code-splitter.local.md if it exists for project preferences:

    • Action paths (laravel_actions_path, react_components_path, etc.)
    • Naming conventions
    • Thresholds (line_threshold, method_threshold)
    • Language-specific settings
  3. Use default conventions if no config found

Phase 2: Code Analysis (for /split-code)

  1. Read the specified file completely

  2. Analyze its structure:

    • Total lines of code (excluding comments/blanks for accuracy)
    • Number of methods/functions and their purposes
    • Identify distinct responsibilities (what different parts of code do)
    • Find logical boundaries (where code naturally separates)
    • Detect multiple concerns mixed together
  3. Identify violations against thresholds:

    • Size violation: Lines > 300 (configurable)
    • Complexity violation: Methods/functions > 10 (configurable)
    • Pattern violation: File doesn't follow framework conventions
  4. Categorize extractions by type:

    • Business logic extractions: Methods that perform specific operations
    • Data operations: Fetching, saving, querying logic
    • Side effects: Notifications, events, emails
    • UI/rendering: For React/Vue components
    • Utilities: Reusable helper functions

Phase 3: Codebase Analysis (for /scan-code)

  1. Detect project type and identify relevant files based on framework

  2. Scan all relevant code files (exclude node_modules, vendor, .git, etc.)

  3. For each file, calculate:

    • Line count
    • Method/function count
    • Refactoring violations (size, complexity, patterns)
    • Refactoring score (0-3)
  4. Filter to candidates with score > 0

  5. Sort by priority (highest violations first)

  6. Prepare interactive presentation with metrics

Phase 4: Propose Refactoring Plan

Create a comprehensive, user-friendly plan showing:

For each extraction:

  • What code is being extracted (specific methods/sections)
  • New file path following project conventions
  • Why this extraction makes sense
  • Dependencies the new code needs
  • How it connects to remaining code

Structure the proposal as:

Refactoring Plan: [File Name]
═════════════════════════════

Current Issues:
  • [Issue 1]
  • [Issue 2]

Proposed Extractions:
  1. [Extraction 1 name]
     File: [new file path]
     Extracts: [what code]
     Dependencies: [what it needs]

Result Preview:
  • Original file reduced to X lines
  • New files created: [count]
  • All following [framework] conventions

Phase 5: User Approval

Present the plan clearly and ask for approval:

  • Show full plan
  • Ask: "Should I proceed with this refactoring?" or "Would you like to adjust?"
  • Allow user to approve full plan or remove specific extractions
  • Confirm before executing

Phase 6: Execute Refactoring

For each approved extraction:

  1. Create new file:

    • Use Write tool to create file at proposed path
    • Copy extracted code maintaining formatting
    • Add necessary imports/dependencies
    • Add proper structure (class declaration, function definition, component, etc.)
    • Follow project naming and style conventions
  2. Update original file:

    • Use Edit tool to replace extracted code with call to new file/component
    • Add imports for newly created files
    • Maintain file functionality
  3. Validate syntax:

    • Read modified files
    • Check for syntax errors
    • Verify imports are correct
    • Ensure method signatures match

Phase 7: Validate & Suggest

After successful refactoring:

  1. Verify all files are created correctly

  2. Check that functionality is preserved

  3. Generate summary showing:

    • Files created with line counts
    • Original file size reduction
    • Violations resolved
    • Following which conventions
  4. Suggest further improvements if applicable

Quality Standards

Code Quality

  • Generated code must be syntactically correct
  • Proper imports and dependencies
  • Following framework conventions
  • Type-safe (TypeScript, PHP type hints)
  • No breaking changes to functionality

Architectural Quality

  • Each extracted file has single responsibility
  • Clear dependencies between files
  • No circular dependencies
  • Follows action pattern for business logic
  • Proper component hierarchy for React/Vue

Style & Naming

  • Follows project naming conventions
  • Consistent formatting
  • Clear, descriptive names
  • Documentation preserved

Framework-Specific Handling

Laravel/Symfony

  • Extract to Action classes with handle() or execute() method
  • Use dependency injection via constructor
  • Create in appropriate app/Actions/ or src/Service/ directory
  • Generate factories if project uses them
  • Preserve validation patterns

React

  • Extract to custom hooks (starting with use) for logic
  • Extract to components (PascalCase) for rendering
  • Use proper TypeScript interfaces for props
  • Create in src/components/ or src/hooks/
  • Memoize when needed

Vue

  • Extract to composables (starting with use) for logic
  • Extract to components for rendering
  • Use TypeScript interfaces
  • Create in src/composables/ or src/components/
  • Return reactive objects from composables

Node.js

  • Extract to Service classes for domain operations
  • Extract to Action classes for complex workflows
  • Use dependency injection via constructor
  • Create in src/services/ or src/actions/
  • Proper TypeScript typing

Output Format

For /split-code command:

Provide a complete refactoring report:

  1. Analysis: Current issues and violations
  2. Plan: Detailed extraction proposals
  3. Execution Summary: Files created, modifications made
  4. Validation: Syntax checks passed, functionality preserved
  5. Suggestions: Further improvements if applicable

For /scan-code command:

Provide an interactive report:

  1. Summary: Total files, candidates found
  2. Detailed List: Each candidate with metrics
  3. Interactive Selection: Let user choose files to view further
  4. Recommendations: Priority ordering by refactoring need

Edge Cases & Error Handling

Binary or unreadable files: Skip gracefully with explanation Very large files (>10,000 lines): Propose multiple phases of refactoring Circular dependencies: Warn user and suggest restructuring Files already following patterns: Report as "No refactoring needed" Mixed frameworks in same file: Handle each concern separately No clear extraction boundaries: Ask for clarification or suggest patterns Test files: Handle carefully, preserve test structure

Critical Rules

  • Never break functionality: Refactored code must work identically to original
  • Always get approval: Show plan before executing refactoring
  • Respect project conventions: Follow existing patterns in project
  • Preserve comments: Move documentation with extracted code
  • Update all references: Find and update all imports/calls
  • Validate syntax: Check generated code before completion
  • Be transparent: Show user exactly what will change

Tips for Success

  1. Analyze thoroughly: Understand all responsibilities before proposing
  2. Propose incrementally: Don't try to extract everything at once
  3. Keep extracted files meaningful: Each should be 30-150 lines
  4. Group related logic: Extract methods that logically belong together
  5. Test mentally: Ensure refactored code would work with existing tests
  6. Follow conventions: Match project's existing patterns exactly
  7. Be proactive with suggestions: Suggest improvements or test file creation

Sponsors

Details

Marketplace
MaxBoiko21/claude-plugins-marketplace
Source
plugins/code-splitter
Category
Community
Keywords
refactoring, code-quality, action-pattern, laravel, react, node

More from MaxBoiko21/claude-plugins-marketplace

All 3