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:
- Guideline compliance — align code with coding-guidelines.md, architecture.md, styling.md, and testing.md
- Testability — restructure code so
/optimus:unit-testcan 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.mdand.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:
deepflag (present/absent)harnesskeyword afterdeep(present/absent)- A number immediately after
deepordeep harness→ iteration cap (optional, default 8, hard cap 10) - 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) → setfocus="testability" - If remaining unquoted text contains standalone
guidelines(case-insensitive) → setfocus="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)
- If remaining unquoted text contains standalone
- Everything else → scope instructions (natural language)
Examples:
/optimus:refactor→ full project, normal mode/optimus:refactor "focus on auth module"→ scope to auth, normal mode/optimus:refactor testability→ full project, normal mode, focus=testability/optimus:refactor guidelines→ full project, normal mode, focus=guidelines/optimus:refactor testability "focus on src/api"→ scope to src/api, focus=testability/optimus:refactor deep→ full project, deep (8 iterations)/optimus:refactor deep 10 backend→ scope to backend, deep (10 iterations)/optimus:refactor deep guidelines→ full project, deep, focus=guidelines/optimus:refactor deep harness→ harness mode, 8 iterations, full project/optimus:refactor deep harness testability→ harness mode, focus=testability
If the iteration cap exceeds 10, clamp it to 10 and warn: "Iteration cap clamped to 10 (maximum)." If the iteration cap is less than 1, clamp it to 1 and warn: "Iteration cap clamped to 1 (minimum)."
Scope resolution
- If scope provided in arguments → use it directly. Map the user's description to directory paths by scanning the project structure. No
AskUserQuestionneeded. - 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: Deep Mode Activation
Harness mode detection
If the system prompt contains HARNESS_MODE_ACTIVE, 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 Step 8 apply/output protocol). Then proceed through Step 1's scope resolution (branch-diff path only — no AskUserQuestion), Step 3, and Step 4 — skip only the Step 2 deep-mode confirmation. If scope_files.current is non-empty in the progress file, treat it as the pre-resolved scope (the harness pre-populated it from the feature-branch diff) and skip the Step 1 scope resolution entirely.
If HARNESS_MODE_ACTIVE is NOT in the system prompt, continue with the standard interactive flow below.
Skill-triggered harness invocation
If the harness keyword was detected in Step 1, read the Skill-Triggered Invocation section of $CLAUDE_PLUGIN_ROOT/references/harness-mode.md and follow its steps. Pass:
skill_name=refactorscope= scope text from Step 1 argument parsingmax_iterations= parsed iteration cap from Step 1 (if specified)focus= focus keyword from Step 1 (if detected)
The reference protocol presents the command and stops. Do not proceed to Step 3 or any remaining steps.
Interactive deep mode
If the deep flag was detected in Step 1, activate deep mode. Deep mode loops analysis-apply cycles (Steps 4–8) until clean or the iteration cap is reached.
Before proceeding, check whether a test command is available (from .claude/CLAUDE.md). If no test command exists, deep mode's auto-apply loop has no safety net — fall back to normal mode and warn: "Deep mode requires a test command for safe auto-apply. Falling back to normal mode — re-run /optimus:init to set up test infrastructure first." Set deep-mode to false. Then continue with the standard single-pass flow.
If a test command is available, warn the user:
Deep mode runs up to [cap] iterative refactoring passes. Each iteration is a full multi-agent analysis cycle — credit and time consumption multiplies with iteration count. Fixes are applied automatically at each iteration without per-change approval. Low test coverage increases the chance of undetected breakage; consider running
/optimus:unit-testfirst to strengthen the safety net. Each iteration also accumulates context — on large codebases, output quality may degrade in later iterations.Test command:
[test command from CLAUDE.md]
Then use AskUserQuestion — header "Deep mode", question "Proceed with deep mode?":
- Start deep mode — "Run iterative refactoring until clean (max [cap] iterations)"
- Normal mode — "Single pass with manual approval instead"
Tell the user: Tip: For large codebases or extended sessions, re-run with /optimus:refactor deep harness to launch the external harness with fresh context per iteration.
If the user did not invoke with deep, skip this ste