Skip to main content
ClaudeWave
Skill58 estrellas del repoactualizado 2d ago

refactor

Refactors existing code for guideline compliance and testability using 4 parallel analysis agents (guideline compliance, testability barriers, duplication/consistency, code-simplifier). Two goals — align code with project guidelines AND make untestable code testable so /optimus:unit-test can safely increase coverage. Use after /optimus:init to align existing code, before /optimus:unit-test to remove testability barriers, or periodically to prevent tech debt. Supports "testability" focus (after unit-test flags untestable code) or "guidelines" focus (after init establishes rules) to prioritize finding categories, and flexible scoping. For iterative refactor in a loop, use `/optimus:refactor-deep`.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/oprogramadorreal/optimus-claude /tmp/refactor && cp -r /tmp/refactor/skills/refactor ~/.claude/skills/refactor
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Project-Wide Code Refactoring

Analyze existing source code against the project's coding guidelines using 4 parallel agents to find guideline violations, testability barriers, cross-file duplication, and pattern inconsistency. Present a prioritized refactoring plan, then apply only user-approved changes with test verification.

Two primary goals:
1. **Guideline compliance** — align code with coding-guidelines.md, architecture.md, styling.md, and testing.md
2. **Testability** — restructure code so `/optimus:unit-test` can safely increase coverage without risky refactoring

The code-simplifier agent guards new code after every edit — this skill is the on-demand complement for restructuring existing code across the project.

## Step 1: Verify Prerequisites and Determine Scope

### Multi-repo workspace detection

Read `$CLAUDE_PLUGIN_ROOT/skills/init/references/multi-repo-detection.md` for workspace detection. If a multi-repo workspace is detected, resolve prerequisites per-repo:
- Determine which repo(s) the scope targets (from file paths, user selection, or changed files)
- Load that repo's `.claude/CLAUDE.md` and `.claude/docs/` as prerequisites (not the workspace root)
- If scope spans multiple repos, load each repo's docs independently and apply per-repo context when analyzing that repo's files
- If no repo can be determined, ask the user which repo to analyze

### Prerequisite check

Read `$CLAUDE_PLUGIN_ROOT/skills/init/references/prerequisite-check.md` and apply the prerequisite check (CLAUDE.md + coding-guidelines.md existence, fallback logic).

### Parse invocation arguments

Extract from the user's arguments:
1. Focus keyword detection — match only **standalone unquoted tokens** (not inside quotes or part of longer words):
   - If remaining unquoted text contains standalone `testability` (case-insensitive) → set `focus` = `"testability"`
   - If remaining unquoted text contains standalone `guidelines` (case-insensitive) → set `focus` = `"guidelines"`
   - Otherwise → `focus` = null (balanced — current behavior)
   - The focus keyword is consumed from the remaining text (not passed as scope)
   - If both keywords appear as standalone tokens, use the first one and warn: "Multiple focus keywords detected — using '[first]'. Run separate passes for each focus."
   - **Safe examples** (keyword NOT consumed — stays as scope):
     - `/optimus:refactor "improve testability in auth"` → focus=null, scope="improve testability in auth" (inside quotes)
     - `/optimus:refactor "fix guidelines compliance"` → focus=null, scope="fix guidelines compliance" (inside quotes)
2. Everything else → scope instructions (natural language)

Examples:
- `/optimus:refactor` → full project
- `/optimus:refactor "focus on auth module"` → scope to auth
- `/optimus:refactor testability` → full project, focus=testability
- `/optimus:refactor guidelines` → full project, focus=guidelines
- `/optimus:refactor testability "focus on src/api"` → scope to src/api, focus=testability

For iterative refactor in a loop, use `/optimus:refactor-deep` instead.

### Scope resolution

- **If scope provided in arguments** → use it directly. Map the user's description to directory paths by scanning the project structure. No `AskUserQuestion` needed.
- **If no scope provided** → use `AskUserQuestion` — header "Scope", question "What scope would you like to refactor?":
  - **Full project** — "All source directories — best for first run or periodic review"
  - **Directory** — "Specific path(s) — best for targeted cleanup"
  - **Changed since** — "Files modified since a commit, tag, or date — incremental review"

Default to **full project** if the user just says "refactor" without specifying.

For **changed since**: use `git diff --name-only <ref>...HEAD` for commit SHAs, branch names, and tags. For relative dates, use `git log --no-merges --since="2 weeks ago" --format= --name-only` instead (`--since` is a `git log` flag, not `git diff`). Filter to source files only (apply the exclusion rules from Step 3).

For monorepos with **full project** scope: ask which subprojects to include (default: all). For **directory** scope: auto-detect which subproject the path belongs to.

## Step 2: Inline Harness Mode Detection

If your invocation prompt body contains `HARNESS_MODE_INLINE`, you are running inside the `/optimus:refactor-deep` or `/optimus:unit-test-deep` orchestrator as a single iteration. Read `$CLAUDE_PLUGIN_ROOT/references/harness-mode.md` and follow its single-iteration execution protocol. The reference covers progress file reading, state initialization, scope and file-list rules, and step overrides (including the apply/output protocol). If `scope_files.current` is non-empty in the progress file, treat it as the pre-resolved scope (the orchestrator pre-populated it from the feature-branch diff) and skip the Step 1 scope resolution entirely. Proceed through Steps 3, 4, 5, and 6 — skip the Step 7 user confirmation (the orchestrator handles approval upfront), apply the fixes mechanically, then emit the structured JSON via the harness-mode output protocol and stop. Do not use `AskUserQuestion`. Do not loop.

If `HARNESS_MODE_INLINE` is NOT present, continue with the standard interactive flow below.

## Step 3: Load Project Context and Map Analysis Areas

### Load constraint docs

Read `$CLAUDE_PLUGIN_ROOT/skills/init/references/constraint-doc-loading.md` for the full document loading procedure (single project and monorepo layouts, scoping rules).

These files define the rules. Every suggestion must be justified by what these docs establish — never impose external preferences.

### Exclude git submodules

Apply the "Submodule Exclusion" rule from `$CLAUDE_PLUGIN_ROOT/skills/init/references/constraint-doc-loading.md` — exclude submodule directories from the analysis.

### Map analysis areas

Within the chosen scope (Step 1), identify source directories. Skip non-source:

- **Dot-directories**: `.git`, `.github`, `.vscode`, `.idea`, `
code-simplifierSubagent

Simplifies and refines code for clarity, consistency, and maintainability while preserving all functionality. Focuses on recently modified code unless instructed otherwise.

test-guardianSubagent

Monitors test coverage gaps when testable code is added or modified. Does not write tests — only flags what needs testing.

brainstormSkill

>-

branchSkill

Creates and switches to a new, conventionally named branch — derives the name from an inline description, conversation context, or local git diffs. Preserves all local changes. Never commits or pushes. Use when you want a properly named branch for new or in-progress work.

code-review-deepSkill

Iterative auto-fix code review — runs `/optimus:code-review` in a fresh subagent context per iteration, applies fixes, runs tests, bisects failures, and continues until convergence or the iteration cap (default 8, hard cap 20). Each iteration runs in an isolated subagent so context does not accumulate. Requires a test command in .claude/CLAUDE.md. Use when single-pass review leaves issues or for thorough cleanup before a release.

code-reviewSkill

Reviews local changes, PRs/MRs, or branch diffs against project coding guidelines using 5 to 7 parallel review agents (bug detection, security/logic, guideline compliance x2, code simplification, test coverage, contract quality). Use before committing, on open PRs/MRs, or to review any branch diff. HIGH SIGNAL only: real bugs, logic errors, security concerns, and guideline violations. For iterative auto-fix in a loop, use `/optimus:code-review-deep`.

commit-messageSkill

Suggests conventional commit messages by analyzing staged, unstaged, and untracked git changes — read-only, never commits. Use when a commit message suggestion is needed without actually committing.

commitSkill

Stages, commits, and optionally pushes local changes with a conventional commit message — analyzes diffs, generates the message, confirms with the user, and commits. On protected branches, offers to create a feature branch automatically. Multi-repo aware. Use when ready to commit work in one step.