oma-refactor
oma-refactor plans and executes behavior-preserving code restructuring through incremental, safety-net-gated transformations targeting code smells, technical debt, and legacy complexity. Use it to improve readability and maintainability via extract-method, rename, decompose, or seam-discovery workflows, preceded by characterization tests where coverage is weak, with each refactoring committed separately from any behavior changes.
git clone --depth 1 https://github.com/first-fluke/oh-my-agent /tmp/oma-refactor && cp -r /tmp/oma-refactor/.agents/skills/oma-refactor ~/.claude/skills/oma-refactorSKILL.md
# Refactor Agent - Behavior-Preserving Restructuring Specialist
## Scheduling
### Goal
Improve internal code structure - readability first - without changing observable behavior, through small verified transformations, each gated by a safety net (tests / tooling / types) and committed separately from any behavior change.
### Intent signature
- User asks to refactor, clean up, restructure, modernize, de-duplicate, or "make this code maintainable/readable".
- User mentions code smells, technical debt, legacy code, long methods/files, god classes, hotspots, characterization tests, or extract/move/rename transformations.
- User asks "where should we refactor first?" or wants a refactoring plan/priority for a codebase.
### When to use
- Executing a refactoring on specific files/modules (extract, move, rename, decompose, pattern/idiom alignment)
- Preparatory refactoring before a feature ("make the change easy, then make the easy change")
- Legacy (brownfield) rescue: seam discovery + characterization tests, then restructuring
- Refactoring target selection and prioritization (smells + SATD + hotspot = churn x complexity)
- Auditing whether code is safe to refactor now (coverage breadth x mutation strength x flakiness)
### When NOT to use
- Fixing a reported bug or failing behavior -> use `oma-debug` (refactoring must not change behavior)
- Security/performance/accessibility review or quality audit -> use `oma-qa`
- System design, module boundary decisions, ADRs, convention changes -> use `oma-architecture` (a convention/pattern change is an architecture decision, not a local refactoring)
- DB schema design or migration mechanics -> use `oma-db` (this skill only plans the expand-contract sequence)
- Commit splitting / staging mechanics -> use `oma-scm`
- Performance optimization as a goal -> out of scope by definition (tuning is a side effect, never the objective)
### Expected inputs
- `target`: file/module/path, smell report, SATD marker, or the feature request motivating preparatory refactoring
- `verification`: project test command(s) per the tool registry; coverage/mutation tooling if available
- `constraints`: coding guide / conventions, regulated-environment flags, merge-window concerns
- Optional: prior metric reports, hotspot data, ADRs touching the target area
### Expected outputs
- Refactored code as a sequence of atomic, refactor-only commits (no test changes mixed in)
- Safety-net additions when missing (characterization / golden-master tests) as separate commits
- Before/after report: metric delta (cyclomatic/cognitive complexity, size, coupling) + readability verdict
```yaml
outputs:
- name: report
description: refactoring plan or before/after report
artifact: ".agents/results/refactor/*.md"
required: false
```
### Dependencies
- `resources/definition.md` (invariant definition: 5 properties, boundaries, destination principle, inline evidence)
- `resources/measurement.md` (4-layer measurement + git forensics commands)
- `resources/governance.md` (org parameters: budget floor, 500-line gate, tool registry)
- Serena MCP symbol/reference tools; project test runners per registry (vitest / pytest / flutter_test)
- Git history for churn/ownership/hotspot analysis
### Control-flow features
- Branches by safety-net state (greenfield vs brownfield), statefulness (code-only vs expand-contract), and verification outcome (pass vs Mikado revert)
- Reads code/history/metrics; writes code, tests (in separate commits), and reports
- Stops and routes to `oma-architecture` when the change requires a convention/boundary decision
## Structural Flow
### Entry
1. Establish what motivates the refactoring (smell, SATD, hotspot, or upcoming feature) and the target scope.
2. Diagnose the safety net for that scope: coverage of changed lines, test determinism (flakiness), mutation strength if measurable.
3. Identify the destination form: the language idiom and codebase convention the result must match.
### Scenes
1. **PREPARE**: Classify greenfield (safety net exists) vs brownfield (build net first); check size gates and hotspot rank; confirm two-hats scope (no feature/bug work mixed in).
2. **ACQUIRE**: Read target code via symbol tools; collect metrics (complexity, size, coupling) and git signals (churn, ownership); read the coding guide for conventions.
3. **REASON**: Decompose the goal into a sequence of named atomic transformations; for stateful targets plan expand-contract; verify each step is independently verifiable and revertible.
4. **ACT**: Apply ONE transformation; prefer deterministic engines (IDE rename, codemod, ast-grep) over freehand edits.
5. **VERIFY**: Re-run existing tests unchanged. Pass -> commit (refactor-only) -> next transformation. Repeated failure -> Mikado: record the broken prerequisite, revert fully, recurse on the prerequisite first.
6. **FINALIZE**: Before/after metric delta + readability judgment (metric improvement alone is not success); report follow-ups discovered but deliberately not done.
### Transitions
- If the safety net is missing or weak (low diff coverage, flaky, no assertions), write characterization / golden-master tests FIRST, committed separately, before touching production code.
- If verification fails repeatedly, switch to the Mikado method: never carry a half-broken tree forward.
- If the right fix is a convention or pattern change (new dialect), stop and route to `oma-architecture` for an ADR + ratchet plan.
- If the target involves persisted state or external consumers, plan expand-contract (parallel change) with feature flags; deployment, not commit, becomes the unit of incrementality.
- If a behavior bug is discovered mid-refactoring, record it and route to `oma-debug`; do not fix it in the refactor commit.
- If the work is large enough to collide with teammates' branches, recommend announcement + short merge window; register bulk mechanical commits in `.git-blame-ignore-revs`.
### Failure and recovery
| Failure | Recovery>
Architecture specialist for software/system design, module and service boundaries, tradeoff analysis, and stakeholder synthesis. Uses context-aware methods such as diagnostic routing, design-twice comparison, ATAM-style risk analysis, CBAM-style prioritization, and ADR-style decision records.
Backend specialist for APIs, databases, authentication with clean architecture (Repository/Service/Router pattern). Use for API, endpoint, REST, database, server, migration, and auth work.
Design-first ideation that explores user intent, constraints, and approaches before any planning or implementation. Use for brainstorming, ideation, exploring concepts, and evaluating approaches.
Guide for coordinating PM, Frontend, Backend, Mobile, and QA agents on complex projects via CLI. Use for manual step-by-step coordination and workflow guidance.
Database specialist for SQL, NoSQL, and vector database modeling, schema design, normalization, indexing, transactions, integrity, concurrency control, backup, capacity planning, data standards, anti-pattern review, and compliance-aware database design. Use for database, schema, ERD, table design, document model, vector index design, RAG retrieval architecture, migration, query tuning, glossary, capacity estimation, backup strategy, database anti-pattern remediation work, and ISO 27001, ISO 27002, or ISO 22301-aware database recommendations.
Bug diagnosis and fixing specialist - analyzes errors, identifies root causes, provides fixes, and writes regression tests. Use for bug, debug, error, crash, traceback, exception, and regression work.
>