CommunityCoding & Developmentgithub.com

refactoring-router

Entry-point refactoring and rewrite skill. Use when the user wants to refactor, clean up, improve, simplify, or rewrite a codebase/file/module and needs smell-driven analysis, technique selection, or a new implementation approach. Detects refactor vs rewrite intent, asks type/mode/risk/scope/depth or ambition, then dispatches specialized subagents in an automatic loop. Triggers: "refactor this", "rewrite this", "clean this up", "improve this codebase", "reimplement this".

What is refactoring-router?

refactoring-router is a OpenCode agent skill that entry-point refactoring and rewrite skill. Use when the user wants to refactor, clean up, improve, simplify, or rewrite a codebase/file/module and needs smell-driven analysis, technique selection, or a new implementation approach. Detects refactor vs rewrite intent, asks type/mode/risk/scope/depth or ambition, then dispatches specialized subagents in an automatic loop. Triggers: "refactor this", "rewrite this", "clean this up", "improve this codebase", "reimplement this".

Works with~Claude Code~Codex CLI~Cursor✓OpenCode
npx skills add https://github.com/Bouzidi-Youssef/refactor-skill/tree/HEAD/.opencode/skills/refactoring_router

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation


name: refactoring-router description: Entry-point refactoring and rewrite skill. Use when the user wants to refactor, clean up, improve, simplify, or rewrite a codebase/file/module and needs smell-driven analysis, technique selection, or a new implementation approach. Detects refactor vs rewrite intent, asks type/mode/risk/scope/depth or ambition, then dispatches specialized subagents in an automatic loop. Triggers: "refactor this", "rewrite this", "clean this up", "improve this codebase", "reimplement this".

Refactoring & Rewrite Router

Top-level dispatcher for smell-driven refactoring and behavior-preserving rewrites. When the user asks to refactor or rewrite, do not work alone. Operate as an orchestrator: scan, classify, plan, then spawn specialized subagents to implement, critique, and verify in an automatic loop.

Core operating model

  • Orchestrator only. The main agent coordinates; subagents do the specialized work.
  • Work on a copy. Never refactor the original target directly.
  • ROI over caution. Do not skip high-value, low/medium-risk refactors because they "cost effort" or might not please the user. Judge by reward/risk, not by time/effort or fear of overstepping. Codebase size is not an excuse to avoid meaningful structural improvement.
  • Autonomy is configurable. Before starting, detect intent (Refactor vs Rewrite). For Refactor, ask refactor type (when broad/ambiguous), mode, risk tolerance (0-10), scope, and depth. For Rewrite, ask ambition (Careful/Normal/Ambitious), mode, risk tolerance, and scope. Scale process to scope, type, and intent.
  • Evidence-based refactoring. Every change must map to a concrete smell, file/symbol, and base skill.
  • Behavior preservation by default. Unless the user explicitly requests behavior change, keep observable behavior the same.

Execution setup (ask upfront)

Detect intent first:

  • Rewrite if the user says "rewrite", "reimplement", "redesign the implementation", "build again", or clearly asks for a new approach/perspective.
  • Refactor if the user says "refactor", "clean up", "simplify", "improve structure", or asks for smell-driven incremental improvement.
  • If ambiguous, ask: "Do you want an incremental refactor, or a behavior-preserving rewrite with a new approach?"

1) Intent-specific setup

If Rewrite intent

Load codebase_rewrite skill. Ask:

  • Ambition level (required):
    LevelIntentRisk
    CarefulConservative reimplementation; minimal design changeLow-Medium
    NormalFresh but grounded redesign; new internal structure where justifiedMedium
    AmbitiousBold reimplementation; rethink approach/patterns, aggressively simplify conceptsMedium-High
  • Execution mode, Risk tolerance (0-10), Scope size as below.
  • Refactor-type goals are still useful as input (code-level/structural/architectural/complexity reduction smells to solve), but the method is rewrite-on-copy with verification, not incremental patching.

If Refactor intent

When the request is broad (e.g. "refactor this codebase"), you must ask the refactor type question.

Ask using the question tool with multiple: true:

What kind of refactor do you want?

OptionScopeSkill / domain
Code-level refactoringFunctions, classes, conditionals, loops, duplication, local design smellsRouter code-level catalog (categories 1-5 below)
Structural / Organizational RefactoringFiles, directories, module boundaries, naming/layout, imports/dependencies, feature groupingstructural_organizational_refactoring
Architectural RefactoringSystem components, boundaries, dependency/data/communication architecture, patternsarchitectural_refactoring
Complexity Reduction / SimplificationOver-engineering, unnecessary abstractions, compatibility residue, excessive indirection, redundant state, over-generalization, defensive over-programming, premature extensibility, control-flow complexitycomplexity_reduction

Rules:

  • User may select more than one, or all.
  • Dominance/order: Architectural → Structural/Organizational → Code-level → Complexity Reduction. Architectural dominates and takes more time. Complexity Reduction runs last as a final simplifier pass to remove noise/over-engineering introduced or left behind.
  • If the user already specified a clear type (e.g. "extract this function", "reorganize folders", "move to hexagonal", "simplify/remove over-engineering"), do not force the question; confirm the inferred type briefly.
  • For Standard/Deep refactors, recommend including Complexity Reduction as a final pass, especially after high-risk or architectural changes.

2) Execution mode

ModeWhen to useHuman intervention
Fully autonomousUser wants maximum progress; trusts agent expertiseNone, except critical blockers (destructive risk, missing access, truly ambiguous behavior the agent cannot safely infer)
CheckpointedUser wants control over key decisionsAgent pauses and asks at decision boundaries

Checkpointed decision boundaries (ask before proceeding):

  • Structural/design direction with meaningful tradeoffs (e.g. introduce classes, split files/modules, change architecture).
  • Public API/contract changes, behavior changes, or semantic-model changes.
  • Risky refactors where verification is weak or ambiguous.
  • Scope expansion beyond what the user asked for.

3) Risk tolerance (0-10)

Ask: "On a scale of 0-10, how much refactor risk can I take? 0 = very conservative, 10 = maximum risk; high-risk tasks are not deferred at 10."

ScorePostureWhat to do
0-2Very conservativeOnly low-risk, clearly behavior-preserving refactors with strong evidence/verification. Defer medium/high-risk items.
3-4ConservativePrefer low-risk refactors; include medium-risk only when verification is good and value is clear.
5-6BalancedTake low/medium-risk refactors; attempt high-risk only with strong justification and verification plan.
7-8AggressiveTake medium/high-risk refactors when ROI is strong; do not defer just because risky. Add extra verification/critique.
9-10MaximumDo not defer high-risk refactors solely because they are risky. Still evidence-based, behavior-preserving by default, and verified as much as possible; clearly report residual risk.

Risk means refactor/regression/contract/verification risk, not intentional behavior change. Behavior preservation remains the default unless the user explicitly requests behavior change.

4) Scope size

ScopeTypical caseDefault orchestration
Small1 file, <~500 LOCLean loop: 1 Scanner (full catalog), 1 Planner, 1 Implementer, 1 Reviewer (Verifier+Critic combined) or separate only if needed; no parallel lens swarm; lightweight blackboard
MediumFew files / small module2-3 lens scanners, Planner, 1-2 Implementers, Verifier, Critic; full blackboard
LargeMulti-module/codebaseFull parallel lens scan (up to 5), Planner, parallel Implementers, separate Verifier/Critic, full blackboard, session resumption

5) Depth (Refactor intent; Rewrite uses Ambition)

DepthMeaning
LightObvious high-ROI cleanup only; minimal churn
StandardNormal refactor pass; balance clarity and structure
DeepInclude structural/high-churn refactors when ROI is strong; still stop on diminishing returns

Defaults if user is unsure: Code-level refactoring, Fully autonomous, 7/10, Small, Standard for a small file; Code-level refactoring, Fully autonomous, 7/10, Medium, Standard for a small/medium codebase; Checkpointed, 5/10, Medium/Large, Standard when contracts/behavior/architecture are unclear. If Architectural Refactoring is selected, prefer Checkpointed unless the user explicitly wants autonomy and risk tolerance is high.

Subagent personas

Persona files live in .opencode/refactoring-personas/. Before spawning a subagent, read the relevant persona file and include its instructions in the subagent prompt.

PersonaFileResponsibility
Scanner.opencode/refactoring-personas/scanner.mdScan scope (full catalog for Small, or assigned lens for Medium/Large), identify smells, map to category/base skill, produce smell report
Planner.opencode/refactoring-personas/planner.mdMerge/deduplicate reports, prioritize by ROI/risk/depth, create safe ordered batches, define stop criteria
Implementer.opencode/refactoring-personas/implementer.mdApply assigned base-skill refactors on the copy, run narrow checks
Critic.opencode/refactoring-personas/critic.mdReview changes for necessity, risk, scope discipline, over-engineering, diminishing returns
Verifier.opencode/refactoring-personas/verifier.mdRun tests/checks/sanity verification, report PASS/FAIL/INCONCLUSIVE

Scope scaling:

  • Small: 1 Scanner (no lens swarm), 1 Planner, 1 Implementer, 1 Reviewer (combine Verifier+Critic responsibilities in one subagent) unless risk/depth warrants separation.
  • Medium: 2-3 lens scanners, Planner, 1-2 Implementers, separate Verifier and Critic.
  • Large: up to 5 lens scanners, Planner, parallel Implementers, separate Verifier and Critic, session resumption.

Use subagent with agent: "general" unless a narrower agent is clearly better. Spawn independent subagents in parallel only when work is isolated and scope justifies it.

Mandatory setup: copy + backup

Before refactoring:

  1. Identify target scope - file, module, or codebase folder the user wants refactored.
  2. Suggest backup commit. If the target is in a git repo with uncommitted or important state, ask the user to create a backup commit/checkpoint before merging any refactor back. This is a short user-facing safety prompt; do not skip it.
  3. Create a working copy next to the original. Default: copy the target folder/codebase to a sibling path like <name>_refactor_copy or <name>-refactor-copy in the same parent directory as the original. Do not use /tmp by default. Only use /tmp or another location if the user explicitly requests it.
  4. Record paths in all subagent prompts:
    • original_path: read-only original
    • copy_path: editable working copy (sibling of original unless user explicitly chose another location)

Subagents may compare copy vs original to understand intent, craft plans, and validate changes. Only copy_path may be modified.

Collaboration protocol (blackboard + session resumption)

Blackboard files (durable shared state)

Create a blackboard directory inside the copy: copy_path/.refactor/. Subagents read relevant files before working and write their outputs before exiting.

Small scope (lightweight):

copy_path/.refactor/
  state.md          # orchestrator: mode, risk, scope, depth, paths, status
  plan.md           # scanner+planner or planner output: smells, batches, stop criteria
  review.md         # verifier+critic combined, or final verification/critique notes

Medium/Large scope (full):

copy_path/.refactor/
  state.md          # orchestrator: mode, risk, scope, depth, paths, iteration, status
  scan/
    <lens>.md       # scanner lens reports
  plan.md           # planner: merged/deduped smells, batches, stop criteria
  decisions.md      # orchestrator/user decisions, checkpoints, deferred items
  batches/
    batch-XX.md     # implementer: changes, skills used, checks, blockers
  verification.md   # verifier: commands, results, regressions, not verified
  critique.md       # critic: verdict, findings, required revisions
  log.md            # orchestrator: append-only timeline

Rules:

  • Blackboard is for coordination/handoff/audit. It is not a replacement for actual code changes in copy_path.
  • Scale blackboard to scope. Do not create full ceremony for a small single-file refactor.
  • Subagents write to their assigned file(s); avoid conflicting writes. Orchestrator owns state.md, decisions.md, log.md.
  • Every report must include evidence: file/symbol, smell, skill ID, risk/confidence, verification.

Orchestrator as message router

The orchestrator is the scheduler/message bus. It:

  • spawns subagents with the right persona, lens/batch, and blackboard paths;
  • collects results;
  • passes relevant findings to the next subagent;
  • updates state.md/log.md/decisions.md.

Session resumption for critique-fix loops

Use subagent sessionID to continue the same subagent when feedback is about the same work.

  • New concern/scope = spawn a new subagent.
  • Feedback on same work = resume same sessionID.
  • Example: Implementer completes Batch 01 → Critic returns REVISE → Orchestrator resumes Implementer Batch 01 sessionID with critique findings and required revisions.
  • Keep resumed-session prompts focused: what changed in feedback, what to fix, what to re-verify, what files to update.

Automatic refactor/rewrite loop

Scale the loop to intent, refactor type, scope, and depth/ambition. Do not run full-swarm ceremony for a small file.

Rewrite intent

If intent is Rewrite, load codebase_rewrite and follow its workflow. Still use copy + blackboard + subagents + verification. Key differences from incremental refactor:

  • Scan smells/goals first - same smell detection, but output feeds a rewrite proposal.
  • Propose target design before large implementation (in plan.md/rewrite-plan.md): current approach, problems, new approach, preserved behavior/contracts, risks, ambition level. Checkpointed mode asks before large redesign.
  • Implement in verifiable slices on copy_path; avoid big-bang invisible rewrite. Keep runnable when possible.
  • Verify aggressively against original behavior/oracle. Critique for behavior drift, missing requirements, and unnecessary complexity.
  • Final simplifier pass before stop when warranted.
  • Ambition controls design freedom (Careful/Normal/Ambitious), not permission to break behavior.

Type-aware orchestration

  • Code-level only: use the code-level catalog/lenses below.
  • Structural/Organizational: load structural_organizational_refactoring. Scan for layout, decomposition, naming, imports/dependencies, module boundaries. Prefer Medium/Large treatment for codebase-wide moves.
  • Architectural: load architectural_refactoring. Dominates and takes more time. Prefer Checkpointed mode unless user explicitly chose autonomy with high risk tolerance. Use deeper analysis, smaller verified batches, and stronger verification.
  • Complexity Reduction / Simplification: load complexity_reduction. Run as a final simplifier pass after other selected refactors pass quality gates (or as a standalone pass if only selected). Focus on over-engineering, compatibility residue, unnecessary abstraction, excessive indirection, redundant state, over-generalization, defensive over-programming, premature extensibility, and control-flow complexity. Optimize for fewer concepts, not fewer lines.
  • Multiple selected: run in dominance order: Architectural → Structural/Organizational → Code-level → Complexity Reduction. Do not do code-level polish inside boundaries that architectural refactor will replace; re-scan after major boundary changes. After other phases pass, run Complexity Reduction to cut noise/over-engineering before final stop.

Small scope (lean loop)

  1. Initialize lightweight blackboard: create copy_path/.refactor/state.md and plan.md. Record selected refactor type(s).
  2. Scan: spawn 1 Scanner using the catalog for selected type(s) (no lens swarm). For multiple types, scan in dominance order or cover all selected types in one pass with clear labeling.
  3. Plan: spawn 1 Planner to produce 1-3 batches max (Small), ordered by ROI and type dominance. Write plan.md.
  4. Implement: spawn 1 Implementer per batch (usually sequential). Load assigned skill(s) before applying.
  5. Review: spawn 1 Reviewer (combine Verifier+Critic) or separate Verifier/Critic when depth/risk warrants it. Write review.md.
  6. Decide: if REVISE/FAIL, resume same Implementer sessionID with feedback. Stop on pass, diminishing returns, or batch cap.

Medium/Large scope (full loop)

Iteration 0 - Parallel lens scan & plan

  1. Initialize blackboard: create copy_path/.refactor/ (full structure). Write state.md, decisions.md, log.md with selected refactor type(s).
  2. Spawn parallel Scanner subagents by lens (2-3 for Medium, up to 5 for Large) using lenses appropriate to selected type(s). Each writes scan/<lens>.md.
  3. Merge/dedup: spawn Planner to read scan reports, deduplicate, rank by confidence/ROI/risk/risk tolerance/depth/type dominance, and write plan.md. Capture Planner sessionID.

Parallel lens scanners (by refactor type)

Code-level lenses:

Scanner lensFocusCategory skill / IDs
Structurelong/mixed functions, naming, params, locals, extraction, signaturessimplifying_restructuring_functions
Redundancy/Complexitydead code, duplication, complex conditionals, flags, needless delegation/classeseliminating_redundancy_and_unnecessary_complexity
Architecture/Reusabilityresponsibilities, misplaced behavior/data, hierarchies, delegates, parameter objects, value/reference semanticsimproving_architecture_and_reusability
Logic/Algorithmsvariant conditionals, special cases, assertions, query/modifier, construction, parameter/query boundariesimproving_conditional_logic_and_algorithms
Loops/Flowloops, pipelines, phase boundaries, statement ordering, branching flowimproving_loops_and_execution_flow

Structural / Organizational lenses:

Scanner lensFocusBase skill ID
File/Directory Organizationmisplaced files, inconsistent structure, deep nesting, technical vs feature groupingreorganize_file_directory_structure
Decomposition/Consolidationoversized files, fragmented cohesive impls, mixed responsibilities, cross-file duplicationsplit_consolidate_files
Naming/Consistencyfile/dir/module/namespace naming conventions and consistencynormalize_naming_consistency
Dependency/Importscycles, unnecessary cross-dir deps, wrong direction, internal-detail imports, util dumping groundsreorganize_dependencies_imports
Module Boundariesscattered features, unclear ownership, excessive coupling between directoriesdefine_module_boundaries

Architectural lenses (dominant, higher cost):

Scanner lensFocusBase skill ID
Patterns/Stylepattern mismatch, monolith/modular/clean/hex/vertical-slice fit, coupling stylerefactor_architectural_patterns
Component Boundariesoverloaded/fragmented components, fat controllers/handlers, UI with business logic, anemic domain model, missing use-case/presenter boundariesrefactor_component_boundaries, extract_use_case, extract_viewmodel_presenter, push_business_logic_to_domain
Dependency Architecturecycles, dependency direction, layer violations, DIP/ports/adapters, leaky cross-layer typesrefactor_dependency_architecture, fix_layer_violation
Data Architecturedata ownership, domain/persistence entanglement, scattered data access, repository boundaries, model separationrefactor_data_architecture, introduce_repository
Execution/Communicationsync/async coordination, event-driven opportunities/risks, queues/buses, pipeline stagesrefactor_execution_communication

Complexity Reduction / Simplification lenses (final pass):

Scanner lensFocusBase skill ID
Abstraction/Indirectionunnecessary wrappers/layers, middle-men, over-abstractionunnecessary_abstraction, excessive_indirection
Compatibility/Generalitylegacy compat residue, dual APIs, introspection dispatch, speculative generality/extensibilitycompatibility_residue, over_generalization, premature_extensibility
State/Defense/Flowredundant state, defensive over-programming, noisy checks, overcomplicated control flowredundant_state, defensive_over_programming, control_flow_simplification

Scanner prompt rule: report evidence-based smells in assigned lens; obvious out-of-lens smells may be noted briefly as "secondary observations". For Architectural scans, include tradeoffs and migration risk. For Complexity Reduction scans, optimize for fewer concepts, not fewer lines; flag compatibility removal as decision boundary when external consumers may exist.

Iteration N - Execute & evaluate

  1. Implement: spawn Implementer subagents for independent parallel-safe batches (no write overlap). Each loads the assigned domain/category/base skill(s) and writes batches/batch-XX.md. Capture sessionIDs.
  2. Verify: spawn Verifier; writes verification.md. For Structural/Architectural, include build/import/dependency/boundary smoke checks where applicable.
  3. Critique: spawn Critic; writes critique.md.
  4. Orchestrator decision (message routing):
    • REVISE / FAIL: resume responsible Implementer sessionID with feedback when same work; otherwise spawn targeted agent. Update log.md.
    • Plan change needed: resume Planner sessionID or spawn new Planner if scope changed materially.
    • PASS / acceptable INCONCLUSIVE: continue with next batch. Before final stop, if Complexity Reduction is selected, or Critic flagged complexity tax/over-engineering at Standard/Deep depth, run a final simplifier pass: re-read changed code, scan with complexity_reduction lenses, plan only high-ROI simplifications, implement, verify, critique. Keep it lean (1 batch unless clearly justified).
    • New meaningful smells emerge: run another lens scan + Planner merge iteration, respecting type dominance.

Stop criteria

Stop when any of these is true:

  • No actionable smells remain. No high/medium-confidence, worthwhile improvements remain for the selected refactor type(s).
  • Quality gates pass. Verifier/Reviewer PASS (or acceptable INCONCLUSIVE with clear limits and no regressions found) and Critic has no required revisions.
  • Diminishing returns. Remaining findings are cosmetic, speculative, lower value than churn/risk, or add complexity tax. This is a hard stop, especially at Light/Standard depth.
  • Batch cap reached. Small default max 3 batches; Medium 5; Large 7. If Architectural Refactoring is selected, allow up to +2 batches for the architectural phase when ROI is strong and verification is adequate, but still stop on diminishing returns.
  • Risk boundary. Remaining changes require human product/architecture decision, public contract change, or unclear behavior.
  • Iteration limit reached. Default max 3 iterations unless user asks for more.

When stopping, report: what changed, why, checks run, risks/not-verified items, refactor type(s) executed, and how to merge/copy changes back from copy_path to original_path.

Subagent prompt contract

Every subagent prompt must include:

  • Persona name and persona file path/content.
  • original_path (read-only) and copy_path (editable).
  • Blackboard path: copy_path/.refactor/ and specific files to read/write (lightweight for Small scope).
  • Scope/files/symbols.
  • Assigned lens (Scanner) or assigned batch (Implementer), if applicable.
  • Assigned task and expected output format.
  • Intent: Refactor or Rewrite.
  • Selected refactor type(s): Code-level, Structural/Organizational, Architectural, Complexity Reduction (and dominance/order rule if multiple, when applicable).
  • Execution mode (Fully autonomous or Checkpointed), decision boundaries.
  • Risk tolerance (0-10) with posture.
  • Scope size (Small|Medium|Large) and depth (Light|Standard|Deep) for Refactor, or ambition (Careful|Normal|Ambitious) for Rewrite.
  • Rule: Never edit original_path. Only edit copy_path.
  • Rule: Preserve observable behavior unless explicitly instructed otherwise.
  • Rule: No direct user approval prompts from subagents. In Fully autonomous mode, proceed directly. In Checkpointed mode, if a decision boundary is hit, do not guess; report the decision needed and let the orchestrator ask the user.
  • Rule: ROI over caution. Do not skip high-value refactors due to effort/caution; judge by reward/risk/verification.
  • Rule: Honor risk tolerance. At 9-10, do not defer high-risk refactors solely because they are risky; attempt with evidence, verification, and explicit residual-risk reporting.
  • Rule: Respect depth and diminishing returns. Light = obvious high-ROI only. Standard = normal. Deep = structural/high-churn allowed when ROI is strong. Stop when complexity tax exceeds value.
  • Rule: No internal-only compatibility wrappers. Do not add legacy wrappers/adapters/inspect-dispatch hacks for internal-only code or disposable verification scripts unless explicitly required.
  • Rule: Use the blackboard appropriately. Read relevant .refactor files before acting; write assigned report before exiting.
  • Relevant smell report / plan / prior findings / critique feedback. For resumed sessions, include only new feedback and what must change.

Category map

Use this catalog to classify smells and select domain/category skills. Load the relevant skill before applying.

A) Structural / Organizational Refactoring (codebase-level)

Domain skill: structural_organizational_refactoring

Smell signalBase skillID
Files in wrong dirs; inconsistent structure; deep nesting; wrong grouping axisReorganize File/Directory Structurereorganize_file_directory_structure
Oversized/mixed files; fragmented cohesive impls; cross-file duplicationSplit/Consolidate Filessplit_consolidate_files
Inconsistent file/dir/module/namespace namingNormalize Naming & Consistencynormalize_naming_consistency
Circular imports; bad dependency direction; internal-detail imports; util dumping groundReorganize Dependencies & Importsreorganize_dependencies_imports
Scattered features; unclear ownership; excessive cross-dir couplingDefine Module Boundariesdefine_module_boundaries

B) Architectural Refactoring (system-level, dominant)

Domain skill: architectural_refactoring

Smell signalBase skillID
Pattern mismatch; monolith/layered/clean/hex/vertical-slice/coupling painRefactor Architectural Patternsrefactor_architectural_patterns
Overloaded/fragmented components; unclear ownership; unnecessary layersRefactor Component Boundariesrefactor_component_boundaries
Circular/wrong dependencies; missing DIP/ports/adapters; unnecessary major depsRefactor Dependency Architecturerefactor_dependency_architecture
Domain/persistence entanglement; unclear data ownership; boundary model mismatchRefactor Data Architecturerefactor_data_architecture
Fragile sync coupling; wrong async/event/pipeline boundaries; tangled workflowsRefactor Execution/Communicationrefactor_execution_communication
Fat controller/handler; orchestration in transport/UI layerExtract Use Case / Interactorextract_use_case
UI/view contains presentation/business logic; hard to testExtract ViewModel / Presenterextract_viewmodel_presenter
Anemic domain model; rules duplicated outside domainPush Business Logic to Domainpush_business_logic_to_domain
Scattered data access; ORM/SQL leaks across layersIntroduce Repositoryintroduce_repository
Presentation/domain depends on wrong layer; dependency direction invertedFix Layer Violationfix_layer_violation

When multiple refactor types are selected, run in dominance order: Architectural → Structural/Organizational → Code-level → Complexity Reduction. Complexity Reduction runs last as a final simplifier pass.

C) Complexity Reduction / Simplification (cross-cutting, final pass)

Domain skill: complexity_reduction

Smell signalBase skillID
Interface/wrapper/class/layer adds no meaningful benefitRemove Unnecessary Abstractionunnecessary_abstraction
Legacy APIs/adapters/fallbacks/introspection dispatch no longer requiredRemove Compatibility Residuecompatibility_residue
Too many calls/layers/wrappers for simple operationsReduce Excessive Indirectionexcessive_indirection
Same information represented/maintained in multiple places; unused/mode-irrelevant stateRemove Redundant Stateredundant_state
Generic solution for 1-2 concrete cases; speculative generalityReduce Over-Generalizationover_generalization
Repeated checks for impossible/already-validated internal states; exception-based flow hacksReduce Defensive Over-Programmingdefensive_over_programming
Infrastructure for hypothetical future requirements; unused extension points/configRemove Premature Extensibilitypremature_extensibility
Branching/nesting/dispatch/flow more complex than problem requiresSimplify Control Flowcontrol_flow_simplification

1) Simplifying and restructuring functions

Category skill: simplifying_restructuring_functions

Smell signalBase skillID
Coherent block needs a name/reuseExtract Functionextract_function
Unnecessary function indirectionInline Functioninline_function
Complex expression needs local nameExtract Variableextract_variable
Unnecessary temporary variableInline Variableinline_variable
Vague/misleading/outdated nameRename Variablerename_variable
Unclear function signature/paramsChange Function Declarationchange_function_declaration
Callers repeat same statements around callMove Statements into Functionmove_statements_into_function
Callee has behavior not common to all callersMove Statements to Callersmove_statements_to_callers
Related statements separated/definition far from useSlide Statementsslide_statements
Variable serves multiple purposesSplit Variablesplit_variable
Correct but unclear algorithmSubstitute Algorithmsubstitute_algorithm
Inline code duplicates existing functionReplace Inline Code with Function Callreplace_inline_code_with_function_call
Callers unpack many fields from one object into argsPreserve Whole Objectpreserve_whole_object

2) Eliminating redundancy and unnecessary complexity

Category skill: eliminating_redundancy_and_unnecessary_complexity

Smell signalBase skillID
Unused/unreachable code, obsolete pathsRemove Dead Coderemove_dead_code
Multiple conditionals lead to same resultConsolidate Conditional Expressionconsolidate_conditional_expression
Complex conditional/branches obscure intentDecompose Conditionaldecompose_conditional
Deep nesting hides normal path / early exitsReplace Nested Conditional with Guard Clausesreplace_nested_conditional_with_guard_clauses
Boolean/mode flag makes calls unclearRemove Flag Argumentremove_flag_argument
Class mostly forwards to delegate with little valueRemove Middle Manremove_middle_man
Class no longer has enough responsibilityInline Classinline_class
Subclass/superclass distinction adds no valueCollapse Hierarchycollapse_hierarchy
Related functions share same data/conceptCombine Functions into Classcombine_functions_into_class
Related functions derive/enrich same input dataCombine Functions into Transformcombine_functions_into_transform
Same behavior duplicated in multiple placesConsolidate Duplicate Codeconsolidate_duplicate_code

3) Improving architecture and reusability

Category skill: improving_architecture_and_reusability

Smell signalBase skillID
Class/module has multiple responsibilitiesExtract Classextract_class
Behavior belongs in another module/classMove Functionmove_function
Data belongs in another classMove Fieldmove_field
Similar classes share common behavior/dataExtract Superclassextract_superclass
Shared method duplicated in subclassesPull Up Methodpull_up_method
Shared field duplicated in subclassesPull Up Fieldpull_up_field
Superclass method only relevant to some subclassesPush Down Methodpush_down_method
Superclass field only relevant to some subclassesPush Down Fieldpush_down_field
Inheritance is wrong; subclass should use superclassReplace Superclass with Delegatereplace_superclass_with_delegate
Subclass variation is rigid/better composedReplace Subclass with Delegatereplace_subclass_with_delegate
Special-case behavior/data belongs in subtypeExtract Subclassextract_subclass
Subclass no longer justified; field/simple model fitsRemove Subclassremove_subclass
Recurring related parameter groupIntroduce Parameter Objectintroduce_parameter_object
Clients reach through server to delegateHide Delegatehide_delegate
Identity doesn't matter; value semantics fitChange Reference to Valuechange_reference_to_value
Logical identity/shared entity mattersChange Value to Referencechange_value_to_reference
Primitive represents domain concept; validation/formatting scatteredReplace Primitive with Objectreplace_primitive_with_object
Multiple classes share capability; callers need contract/seamExtract Interfaceextract_interface

4) Improving conditional logic and algorithms

Category skill: improving_conditional_logic_and_algorithms

Smell signalBase skillID
Repeated variant/type conditionalsReplace Conditional with Polymorphismreplace_conditional_with_polymorphism
Repeated null/unknown/sentinel handlingIntroduce Special Caseintroduce_special_case
Implicit assumption/invariantIntroduce Assertionintroduce_assertion
Similar functions differ by small valueParameterize Functionparameterize_function
Function both queries and mutatesSeparate Query from Modifierseparate_query_from_modifier
Construction is unclear/limited/complexReplace Constructor with Factory Functionreplace_constructor_with_factory_function
Parameter is redundant/derivableReplace Parameter with Queryreplace_parameter_with_query
Hidden dependency should be explicitReplace Query with Parameterreplace_query_with_parameter
Recurring related parameter groupIntroduce Parameter Objectintroduce_parameter_object

5) Improving loops and execution flow

Category skill: improving_loops_and_execution_flow

Smell signalBase skillID
Imperative loop obscures data transformationReplace Loop with Pipelinereplace_loop_with_pipeline
One loop does multiple independent jobsSplit Loopsplit_loop
Mixed processing stages need clear boundariesSplit Phasesplit_phase
Complex conditional obscures branching intentDecompose Conditionaldecompose_conditional
Related statements are far apart / poorly orderedSlide Statementsslide_statements

Guardrails

  • Never refactor original. Only copy_path gets edits.
  • Copy next to original by default. Do not use /tmp unless the user explicitly requests it.
  • Scale to scope, depth, and refactor type. Small scope = lean loop (1 scanner, 1 planner, 1 implementer, 1 reviewer, lightweight blackboard, max ~3 batches). Medium/Large = fuller orchestration. Light depth = obvious high-ROI only; Deep = structural/high-churn allowed when ROI is strong.
  • Type dominance/order. If multiple refactor types are selected, run Architectural → Structural/Organizational → Code-level → Complexity Reduction. Architectural dominates and takes more time/verification. Complexity Reduction runs last as a final simplifier pass to cut noise and over-engineering; do not skip it when selected.
  • ROI over caution. Do not avoid good refactors because of effort, time, or fear of overstepping. Judge by reward/risk/verification.
  • Honor risk tolerance. 0-10 controls willingness to attempt risky refactors. At 9-10, do not defer high-risk refactors solely for risk; attempt with evidence, verification, and explicit residual-risk reporting. Risk tolerance is not "implement every idea regardless of value".
  • No blind refactors. Every change needs smell evidence and a skill mapping.
  • Parallel lens scanning when justified. Medium/Large: use different lens scanners and dedup before implementation. Small: one full-catalog scanner is enough.
  • No over-engineering / complexity tax. Critic must flag when a refactor adds more complexity/churn than clarity/value. Stop on diminishing returns. Prefer fewer concepts, not fewer lines; never assume existing complexity deserves preservation merely because it exists.
  • Final simplifier pass. Before final stop, run a lean Complexity Reduction pass when selected, or when Standard/Deep depth and Critic/Orchestrator observed complexity tax, compatibility residue, unnecessary abstraction, or over-engineering. Do not turn this into another big refactor; keep only high-ROI simplifications.
  • No internal-only compatibility wrappers. Do not add legacy wrappers, adapters, inspect-based dispatch hacks, or signature shims for internal-only code or disposable verification scripts unless explicitly required. Update internal call sites and temporary scripts instead.
  • Disposable verification scripts stay disposable. Do not let temporary /tmp smoke scripts drive production compatibility design.
  • Preserve behavior. Default is behavior-preserving refactor; behavior changes require explicit user request.
  • Mode-aware autonomy. Fully autonomous: proceed without approval prompts. Checkpointed: pause only at decision boundaries.
  • Be honest about verification. If tests are missing, say what was not verified.
  • Escalate only at boundaries. Ask the user only for backup confirmation, intent/refactor type/mode/risk/scope/depth/ambition selection, scope clarification, checkpoint decisions (in Checkpointed mode), or merge approval.

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

Related Skills