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):
Level Intent Risk Careful Conservative reimplementation; minimal design change Low-Medium Normal Fresh but grounded redesign; new internal structure where justified Medium Ambitious Bold reimplementation; rethink approach/patterns, aggressively simplify concepts Medium-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?
| Option | Scope | Skill / domain |
|---|---|---|
| Code-level refactoring | Functions, classes, conditionals, loops, duplication, local design smells | Router code-level catalog (categories 1-5 below) |
| Structural / Organizational Refactoring | Files, directories, module boundaries, naming/layout, imports/dependencies, feature grouping | structural_organizational_refactoring |
| Architectural Refactoring | System components, boundaries, dependency/data/communication architecture, patterns | architectural_refactoring |
| Complexity Reduction / Simplification | Over-engineering, unnecessary abstractions, compatibility residue, excessive indirection, redundant state, over-generalization, defensive over-programming, premature extensibility, control-flow complexity | complexity_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
| Mode | When to use | Human intervention |
|---|---|---|
| Fully autonomous | User wants maximum progress; trusts agent expertise | None, except critical blockers (destructive risk, missing access, truly ambiguous behavior the agent cannot safely infer) |
| Checkpointed | User wants control over key decisions | Agent 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."
| Score | Posture | What to do |
|---|---|---|
| 0-2 | Very conservative | Only low-risk, clearly behavior-preserving refactors with strong evidence/verification. Defer medium/high-risk items. |
| 3-4 | Conservative | Prefer low-risk refactors; include medium-risk only when verification is good and value is clear. |
| 5-6 | Balanced | Take low/medium-risk refactors; attempt high-risk only with strong justification and verification plan. |
| 7-8 | Aggressive | Take medium/high-risk refactors when ROI is strong; do not defer just because risky. Add extra verification/critique. |
| 9-10 | Maximum | Do 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
| Scope | Typical case | Default orchestration |
|---|---|---|
| Small | 1 file, <~500 LOC | Lean 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 |
| Medium | Few files / small module | 2-3 lens scanners, Planner, 1-2 Implementers, Verifier, Critic; full blackboard |
| Large | Multi-module/codebase | Full parallel lens scan (up to 5), Planner, parallel Implementers, separate Verifier/Critic, full blackboard, session resumption |
5) Depth (Refactor intent; Rewrite uses Ambition)
| Depth | Meaning |
|---|---|
| Light | Obvious high-ROI cleanup only; minimal churn |
| Standard | Normal refactor pass; balance clarity and structure |
| Deep | Include 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.
| Persona | File | Responsibility |
|---|---|---|
| Scanner | .opencode/refactoring-personas/scanner.md | Scan 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.md | Merge/deduplicate reports, prioritize by ROI/risk/depth, create safe ordered batches, define stop criteria |
| Implementer | .opencode/refactoring-personas/implementer.md | Apply assigned base-skill refactors on the copy, run narrow checks |
| Critic | .opencode/refactoring-personas/critic.md | Review changes for necessity, risk, scope discipline, over-engineering, diminishing returns |
| Verifier | .opencode/refactoring-personas/verifier.md | Run 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:
- Identify target scope - file, module, or codebase folder the user wants refactored.
- 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.
- Create a working copy next to the original. Default: copy the target folder/codebase to a sibling path like
<name>_refactor_copyor<name>-refactor-copyin the same parent directory as the original. Do not use/tmpby default. Only use/tmpor another location if the user explicitly requests it. - Record paths in all subagent prompts:
original_path: read-only originalcopy_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 01sessionIDwith 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)
- Initialize lightweight blackboard: create
copy_path/.refactor/state.mdandplan.md. Record selected refactor type(s). - 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.
- Plan: spawn 1 Planner to produce 1-3 batches max (Small), ordered by ROI and type dominance. Write
plan.md. - Implement: spawn 1 Implementer per batch (usually sequential). Load assigned skill(s) before applying.
- Review: spawn 1 Reviewer (combine Verifier+Critic) or separate Verifier/Critic when depth/risk warrants it. Write
review.md. - Decide: if REVISE/FAIL, resume same Implementer
sessionIDwith feedback. Stop on pass, diminishing returns, or batch cap.
Medium/Large scope (full loop)
Iteration 0 - Parallel lens scan & plan
- Initialize blackboard: create
copy_path/.refactor/(full structure). Writestate.md,decisions.md,log.mdwith selected refactor type(s). - 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. - Merge/dedup: spawn Planner to read scan reports, deduplicate, rank by confidence/ROI/risk/risk tolerance/depth/type dominance, and write
plan.md. Capture PlannersessionID.
Parallel lens scanners (by refactor type)
Code-level lenses:
| Scanner lens | Focus | Category skill / IDs |
|---|---|---|
| Structure | long/mixed functions, naming, params, locals, extraction, signatures | simplifying_restructuring_functions |
| Redundancy/Complexity | dead code, duplication, complex conditionals, flags, needless delegation/classes | eliminating_redundancy_and_unnecessary_complexity |
| Architecture/Reusability | responsibilities, misplaced behavior/data, hierarchies, delegates, parameter objects, value/reference semantics | improving_architecture_and_reusability |
| Logic/Algorithms | variant conditionals, special cases, assertions, query/modifier, construction, parameter/query boundaries | improving_conditional_logic_and_algorithms |
| Loops/Flow | loops, pipelines, phase boundaries, statement ordering, branching flow | improving_loops_and_execution_flow |
Structural / Organizational lenses:
| Scanner lens | Focus | Base skill ID |
|---|---|---|
| File/Directory Organization | misplaced files, inconsistent structure, deep nesting, technical vs feature grouping | reorganize_file_directory_structure |
| Decomposition/Consolidation | oversized files, fragmented cohesive impls, mixed responsibilities, cross-file duplication | split_consolidate_files |
| Naming/Consistency | file/dir/module/namespace naming conventions and consistency | normalize_naming_consistency |
| Dependency/Imports | cycles, unnecessary cross-dir deps, wrong direction, internal-detail imports, util dumping grounds | reorganize_dependencies_imports |
| Module Boundaries | scattered features, unclear ownership, excessive coupling between directories | define_module_boundaries |
Architectural lenses (dominant, higher cost):
| Scanner lens | Focus | Base skill ID |
|---|---|---|
| Patterns/Style | pattern mismatch, monolith/modular/clean/hex/vertical-slice fit, coupling style | refactor_architectural_patterns |
| Component Boundaries | overloaded/fragmented components, fat controllers/handlers, UI with business logic, anemic domain model, missing use-case/presenter boundaries | refactor_component_boundaries, extract_use_case, extract_viewmodel_presenter, push_business_logic_to_domain |
| Dependency Architecture | cycles, dependency direction, layer violations, DIP/ports/adapters, leaky cross-layer types | refactor_dependency_architecture, fix_layer_violation |
| Data Architecture | data ownership, domain/persistence entanglement, scattered data access, repository boundaries, model separation | refactor_data_architecture, introduce_repository |
| Execution/Communication | sync/async coordination, event-driven opportunities/risks, queues/buses, pipeline stages | refactor_execution_communication |
Complexity Reduction / Simplification lenses (final pass):
| Scanner lens | Focus | Base skill ID |
|---|---|---|
| Abstraction/Indirection | unnecessary wrappers/layers, middle-men, over-abstraction | unnecessary_abstraction, excessive_indirection |
| Compatibility/Generality | legacy compat residue, dual APIs, introspection dispatch, speculative generality/extensibility | compatibility_residue, over_generalization, premature_extensibility |
| State/Defense/Flow | redundant state, defensive over-programming, noisy checks, overcomplicated control flow | redundant_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
- Implement: spawn Implementer subagents for independent
parallel-safebatches (no write overlap). Each loads the assigned domain/category/base skill(s) and writesbatches/batch-XX.md. CapturesessionIDs. - Verify: spawn Verifier; writes
verification.md. For Structural/Architectural, include build/import/dependency/boundary smoke checks where applicable. - Critique: spawn Critic; writes
critique.md. - Orchestrator decision (message routing):
- REVISE / FAIL: resume responsible Implementer
sessionIDwith feedback when same work; otherwise spawn targeted agent. Updatelog.md. - Plan change needed: resume Planner
sessionIDor 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_reductionlenses, 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.
- REVISE / FAIL: resume responsible Implementer
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) andcopy_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:
RefactororRewrite. - Selected refactor type(s):
Code-level,Structural/Organizational,Architectural,Complexity Reduction(and dominance/order rule if multiple, when applicable). - Execution mode (
Fully autonomousorCheckpointed), 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
.refactorfiles 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 signal | Base skill | ID |
|---|---|---|
| Files in wrong dirs; inconsistent structure; deep nesting; wrong grouping axis | Reorganize File/Directory Structure | reorganize_file_directory_structure |
| Oversized/mixed files; fragmented cohesive impls; cross-file duplication | Split/Consolidate Files | split_consolidate_files |
| Inconsistent file/dir/module/namespace naming | Normalize Naming & Consistency | normalize_naming_consistency |
| Circular imports; bad dependency direction; internal-detail imports; util dumping ground | Reorganize Dependencies & Imports | reorganize_dependencies_imports |
| Scattered features; unclear ownership; excessive cross-dir coupling | Define Module Boundaries | define_module_boundaries |
B) Architectural Refactoring (system-level, dominant)
Domain skill: architectural_refactoring
| Smell signal | Base skill | ID |
|---|---|---|
| Pattern mismatch; monolith/layered/clean/hex/vertical-slice/coupling pain | Refactor Architectural Patterns | refactor_architectural_patterns |
| Overloaded/fragmented components; unclear ownership; unnecessary layers | Refactor Component Boundaries | refactor_component_boundaries |
| Circular/wrong dependencies; missing DIP/ports/adapters; unnecessary major deps | Refactor Dependency Architecture | refactor_dependency_architecture |
| Domain/persistence entanglement; unclear data ownership; boundary model mismatch | Refactor Data Architecture | refactor_data_architecture |
| Fragile sync coupling; wrong async/event/pipeline boundaries; tangled workflows | Refactor Execution/Communication | refactor_execution_communication |
| Fat controller/handler; orchestration in transport/UI layer | Extract Use Case / Interactor | extract_use_case |
| UI/view contains presentation/business logic; hard to test | Extract ViewModel / Presenter | extract_viewmodel_presenter |
| Anemic domain model; rules duplicated outside domain | Push Business Logic to Domain | push_business_logic_to_domain |
| Scattered data access; ORM/SQL leaks across layers | Introduce Repository | introduce_repository |
| Presentation/domain depends on wrong layer; dependency direction inverted | Fix Layer Violation | fix_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 signal | Base skill | ID |
|---|---|---|
| Interface/wrapper/class/layer adds no meaningful benefit | Remove Unnecessary Abstraction | unnecessary_abstraction |
| Legacy APIs/adapters/fallbacks/introspection dispatch no longer required | Remove Compatibility Residue | compatibility_residue |
| Too many calls/layers/wrappers for simple operations | Reduce Excessive Indirection | excessive_indirection |
| Same information represented/maintained in multiple places; unused/mode-irrelevant state | Remove Redundant State | redundant_state |
| Generic solution for 1-2 concrete cases; speculative generality | Reduce Over-Generalization | over_generalization |
| Repeated checks for impossible/already-validated internal states; exception-based flow hacks | Reduce Defensive Over-Programming | defensive_over_programming |
| Infrastructure for hypothetical future requirements; unused extension points/config | Remove Premature Extensibility | premature_extensibility |
| Branching/nesting/dispatch/flow more complex than problem requires | Simplify Control Flow | control_flow_simplification |
1) Simplifying and restructuring functions
Category skill: simplifying_restructuring_functions
| Smell signal | Base skill | ID |
|---|---|---|
| Coherent block needs a name/reuse | Extract Function | extract_function |
| Unnecessary function indirection | Inline Function | inline_function |
| Complex expression needs local name | Extract Variable | extract_variable |
| Unnecessary temporary variable | Inline Variable | inline_variable |
| Vague/misleading/outdated name | Rename Variable | rename_variable |
| Unclear function signature/params | Change Function Declaration | change_function_declaration |
| Callers repeat same statements around call | Move Statements into Function | move_statements_into_function |
| Callee has behavior not common to all callers | Move Statements to Callers | move_statements_to_callers |
| Related statements separated/definition far from use | Slide Statements | slide_statements |
| Variable serves multiple purposes | Split Variable | split_variable |
| Correct but unclear algorithm | Substitute Algorithm | substitute_algorithm |
| Inline code duplicates existing function | Replace Inline Code with Function Call | replace_inline_code_with_function_call |
| Callers unpack many fields from one object into args | Preserve Whole Object | preserve_whole_object |
2) Eliminating redundancy and unnecessary complexity
Category skill: eliminating_redundancy_and_unnecessary_complexity
| Smell signal | Base skill | ID |
|---|---|---|
| Unused/unreachable code, obsolete paths | Remove Dead Code | remove_dead_code |
| Multiple conditionals lead to same result | Consolidate Conditional Expression | consolidate_conditional_expression |
| Complex conditional/branches obscure intent | Decompose Conditional | decompose_conditional |
| Deep nesting hides normal path / early exits | Replace Nested Conditional with Guard Clauses | replace_nested_conditional_with_guard_clauses |
| Boolean/mode flag makes calls unclear | Remove Flag Argument | remove_flag_argument |
| Class mostly forwards to delegate with little value | Remove Middle Man | remove_middle_man |
| Class no longer has enough responsibility | Inline Class | inline_class |
| Subclass/superclass distinction adds no value | Collapse Hierarchy | collapse_hierarchy |
| Related functions share same data/concept | Combine Functions into Class | combine_functions_into_class |
| Related functions derive/enrich same input data | Combine Functions into Transform | combine_functions_into_transform |
| Same behavior duplicated in multiple places | Consolidate Duplicate Code | consolidate_duplicate_code |
3) Improving architecture and reusability
Category skill: improving_architecture_and_reusability
| Smell signal | Base skill | ID |
|---|---|---|
| Class/module has multiple responsibilities | Extract Class | extract_class |
| Behavior belongs in another module/class | Move Function | move_function |
| Data belongs in another class | Move Field | move_field |
| Similar classes share common behavior/data | Extract Superclass | extract_superclass |
| Shared method duplicated in subclasses | Pull Up Method | pull_up_method |
| Shared field duplicated in subclasses | Pull Up Field | pull_up_field |
| Superclass method only relevant to some subclasses | Push Down Method | push_down_method |
| Superclass field only relevant to some subclasses | Push Down Field | push_down_field |
| Inheritance is wrong; subclass should use superclass | Replace Superclass with Delegate | replace_superclass_with_delegate |
| Subclass variation is rigid/better composed | Replace Subclass with Delegate | replace_subclass_with_delegate |
| Special-case behavior/data belongs in subtype | Extract Subclass | extract_subclass |
| Subclass no longer justified; field/simple model fits | Remove Subclass | remove_subclass |
| Recurring related parameter group | Introduce Parameter Object | introduce_parameter_object |
| Clients reach through server to delegate | Hide Delegate | hide_delegate |
| Identity doesn't matter; value semantics fit | Change Reference to Value | change_reference_to_value |
| Logical identity/shared entity matters | Change Value to Reference | change_value_to_reference |
| Primitive represents domain concept; validation/formatting scattered | Replace Primitive with Object | replace_primitive_with_object |
| Multiple classes share capability; callers need contract/seam | Extract Interface | extract_interface |
4) Improving conditional logic and algorithms
Category skill: improving_conditional_logic_and_algorithms
| Smell signal | Base skill | ID |
|---|---|---|
| Repeated variant/type conditionals | Replace Conditional with Polymorphism | replace_conditional_with_polymorphism |
| Repeated null/unknown/sentinel handling | Introduce Special Case | introduce_special_case |
| Implicit assumption/invariant | Introduce Assertion | introduce_assertion |
| Similar functions differ by small value | Parameterize Function | parameterize_function |
| Function both queries and mutates | Separate Query from Modifier | separate_query_from_modifier |
| Construction is unclear/limited/complex | Replace Constructor with Factory Function | replace_constructor_with_factory_function |
| Parameter is redundant/derivable | Replace Parameter with Query | replace_parameter_with_query |
| Hidden dependency should be explicit | Replace Query with Parameter | replace_query_with_parameter |
| Recurring related parameter group | Introduce Parameter Object | introduce_parameter_object |
5) Improving loops and execution flow
Category skill: improving_loops_and_execution_flow
| Smell signal | Base skill | ID |
|---|---|---|
| Imperative loop obscures data transformation | Replace Loop with Pipeline | replace_loop_with_pipeline |
| One loop does multiple independent jobs | Split Loop | split_loop |
| Mixed processing stages need clear boundaries | Split Phase | split_phase |
| Complex conditional obscures branching intent | Decompose Conditional | decompose_conditional |
| Related statements are far apart / poorly ordered | Slide Statements | slide_statements |
Guardrails
- Never refactor original. Only
copy_pathgets edits. - Copy next to original by default. Do not use
/tmpunless 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
/tmpsmoke 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.