원클릭으로
refactor
Intelligent refactor command. Triggers: refactor, refactoring, cleanup, restructure, extract, simplify, modernize.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Intelligent refactor command. Triggers: refactor, refactoring, cleanup, restructure, extract, simplify, modernize.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
MUST USE for frontend/web UI/UX/visual work: building, styling, redesigning pages/components, React setup, performance audits, visual QA, taste, and polish. Routes four rulesets: design taste router and brand references; perfection for Playwright/Chromium Lighthouse/Core Web Vitals; ui-ux-db palettes/fonts/guidelines; designpowers personas/accessibility/critique/handoff. Triggers: frontend, UI, UX, design, redesign, styling, layout, animation, motion, premium, luxury, minimal, brutalist, Awwwards, DESIGN.md, mockup, React, Lighthouse, accessibility, WCAG, Core Web Vitals, looks generic, make it pretty, like X brand.
MUST USE for ANY work on .py .pyi .rs .ts .tsx .mts .cts .go files. One philosophy: strict types, modern stacks (Pydantic v2 / serde+thiserror / Zod / gin+sqlc+pgx+slog), modern toolchains (uv+basedpyright+ruff / cargo+clippy+miri / Bun+Biome+tsc / gofumpt+golangci-lint v2+nilaway+go-race), parse-don't-validate, exhaustive match, typed errors, no any/unwrap/panic, 250 LOC ceiling, TDD. Routes to references/{python,rust,typescript,rust-ub,go}/. Triggers: write/edit Python/Rust/TypeScript/Go code, new project, gin server, bubbletea TUI, CJK IME, connect-go RPC, sqlc pgx, branded ids, exhaustive match, unsafe Rust, miri, oversized file, refactor, TDD, e2e test, arena, allocator, bumpalo, const fn, const generics, comptime, zero-alloc, bitfield, repr, scopeguard, errdefer, Zig-like, zerocopy, packed struct.
Remove AI-generated code smells (slop) from branch changes or an explicit file list. Locks behavior with regression tests FIRST, then runs categorized cleanup via parallel `deep` agents in batches of 5, then verifies with quality gates. Covers 10 slop categories including performance equivalences, excessive complexity (object annotations, if/elif variant chains), and oversized modules (250+ pure LOC with mandatory modular refactoring). MUST USE when the user asks to "remove slop", "clean AI code", "deslop", "clean up AI-generated code", "remove AI slop", or wants to clean up AI-generated patterns from recent changes. Triggers - "remove ai slops", "clean ai code", "deslop", "cleanup AI generated", "remove AI slop", "clean up AI-generated code", "strip slop", "ai-slop cleanup".
MUST USE after building/changing any UI or when asked whether a page, component, or TUI looks right. Rigorous visual QA across web/page and terminal UIs. Prefer browser:control-in-app-browser for unauthenticated browser/page QA in Codex, then Playwright/agent-browser/dev-browser. Captures screenshot/TUI evidence with bundled diff scripts, runs design-system/functional and visual-fidelity/CJK reviewer passes, then synthesizes a good/bad verdict. Triggers: visual QA, screenshot/pixel diff, UI looks wrong, reference fidelity, design system check, responsive check, CJK text clipping, TUI alignment, box-drawing drift.
(builtin) Initialize hierarchical AGENTS.md knowledge base
Post-implementation review orchestrator. Launches 5 parallel background sub-agents: Oracle (goal/constraint verification), Oracle (code quality), Oracle (security), unspecified-high (hands-on QA execution), unspecified-high (context mining from GitHub/git/Slack/Notion). All must pass for review to pass. MUST USE after completing any significant implementation work. Triggers: 'review work', 'review my work', 'review changes', 'QA my work', 'verify implementation', 'check my work', 'validate changes', 'post-implementation review'.
| name | refactor |
| description | Intelligent refactor command. Triggers: refactor, refactoring, cleanup, restructure, extract, simplify, modernize. |
This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as call_omo_agent(...), task(...), background_output(...), or team_*(...) literally. Translate those examples to Codex native tools:
| OpenCode example | Codex tool to use |
|---|---|
call_omo_agent(subagent_type="explore", ...) | multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false}) |
call_omo_agent(subagent_type="librarian", ...) | multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false}) |
task(subagent_type="plan", ...) | multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false}) |
task(subagent_type="oracle", ...) for final verification | multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"lazycodex-gate-reviewer","fork_context":false}) |
task(category="...", ...) for implementation or QA | multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false}) |
background_output(task_id="...") | multi_agent_v1.wait_agent(...) for mailbox signals |
team_*(...) | Use Codex native subagents via multi_agent_v1.spawn_agent, multi_agent_v1.send_input, multi_agent_v1.wait_agent, and multi_agent_v1.close_agent |
Role-specific behavior must be described in a self-contained message. Use fork_context: false to start the child with only the initial prompt (no parent history); use fork_context: true only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's message. OMO installs these selectable agent roles into ~/.codex/agents/: explorer, librarian, plan, momus, metis, lazycodex-code-reviewer, lazycodex-qa-executor, and lazycodex-gate-reviewer - pass the matching name as agent_type so the child gets that role's model and instructions. If the spawn tool exposes no agent_type parameter, omit it and describe the role inside message. If a code block below conflicts with this section, this section wins.
On multi_agent_v2 sessions the same agent_type applies (the OMO installer exposes it) with fork_turns instead of fork_context. If a code block below conflicts with this section, this section wins.
When translating load_skills=[...], include the requested skill names in the spawned agent's message. If a code block below conflicts with this section, this section wins.
For work likely to exceed one wait cycle, require the child to send WORKING: <task> - <current phase> before long passes and BLOCKED: <reason> only when progress stops. A multi_agent_v1.wait_agent timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly BLOCKED:, or no longer running.
export const REFACTOR_TEMPLATE = `# Intelligent Refactor Command
``` /refactor [--scope=<file|module|project>] [--strategy=<safe|aggressive>]
Arguments: refactoring-target: What to refactor. Can be: - File path: src/auth/handler.ts - Symbol name: "AuthService class" - Pattern: "all functions using deprecated API" - Description: "extract validation logic into separate module"
Options: --scope: Refactoring scope (default: module) - file: Single file only - module: Module/directory scope - project: Entire codebase
--strategy: Risk tolerance (default: safe) - safe: Conservative, maximum test coverage required - aggressive: Allow broader changes with adequate coverage ```
Performs intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:
BEFORE ANY ACTION, classify and validate the request.
| Signal | Classification | Action |
|---|---|---|
| Specific file/symbol | Explicit | Proceed to codebase analysis |
| "Refactor X to Y" | Clear transformation | Proceed to codebase analysis |
| "Improve", "Clean up" | Open-ended | MUST ask: "What specific improvement?" |
| Ambiguous scope | Uncertain | MUST ask: "Which modules/files?" |
| Missing context | Incomplete | MUST ask: "What's the desired outcome?" |
Before proceeding, confirm:
If ANY of above is unclear, ASK CLARIFYING QUESTION:
``` I want to make sure I understand the refactoring goal correctly.
What I understood: [interpretation] What I'm unsure about: [specific ambiguity]
Options I see:
My recommendation: [suggestion with reasoning]
Should I proceed with [recommendation], or would you prefer differently? ```
IMMEDIATELY after understanding the request, create todos:
``` TodoWrite([ {"id": "phase-1", "content": "PHASE 1: Codebase Analysis - launch parallel explore agents", "status": "pending", "priority": "high"}, {"id": "phase-2", "content": "PHASE 2: Build Codemap - map dependencies and impact zones", "status": "pending", "priority": "high"}, {"id": "phase-3", "content": "PHASE 3: Test Assessment - analyze test coverage and verification strategy", "status": "pending", "priority": "high"}, {"id": "phase-4", "content": "PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan", "status": "pending", "priority": "high"}, {"id": "phase-5", "content": "PHASE 5: Execute Refactoring - step-by-step with continuous verification", "status": "pending", "priority": "high"}, {"id": "phase-6", "content": "PHASE 6: Final Verification - full test suite and regression check", "status": "pending", "priority": "high"} ]) ```
Mark phase-1 as in_progress.
Fire ALL of these simultaneously using `call_omo_agent`:
``` // Agent 1: Find the refactoring target call_omo_agent( subagent_type="explore", run_in_background=true, prompt="Find all occurrences and definitions of [TARGET]. Report: file paths, line numbers, usage patterns." )
// Agent 2: Find related code call_omo_agent( subagent_type="explore", run_in_background=true, prompt="Find all code that imports, uses, or depends on [TARGET]. Report: dependency chains, import graphs." )
// Agent 3: Find similar patterns call_omo_agent( subagent_type="explore", run_in_background=true, prompt="Find similar code patterns to [TARGET] in the codebase. Report: analogous implementations, established conventions." )
// Agent 4: Find tests call_omo_agent( subagent_type="explore", run_in_background=true, prompt="Find all test files related to [TARGET]. Report: test file paths, test case names, coverage indicators." )
// Agent 5: Architecture context call_omo_agent( subagent_type="explore", run_in_background=true, prompt="Find architectural patterns and module organization around [TARGET]. Report: module boundaries, layer structure, design patterns in use." ) ```
While background agents are running, use direct tools:
```typescript // Find definition(s) LspGotoDefinition(filePath, line, character) // Where is it defined?
// Find ALL usages across workspace LspFindReferences(filePath, line, character, includeDeclaration=true)
// Get file structure LspDocumentSymbols(filePath) // Hierarchical outline LspWorkspaceSymbols(filePath, query="[target_symbol]") // Search by name
// Get current diagnostics lsp_diagnostics(filePath) // Errors, warnings before we start ```
```bash // Find structural patterns python3 scripts/ast_grep_helper.py search 'function $NAME($$$) { $$$ }' --lang ts src/
sg --pattern '[old_pattern]' --rewrite '[new_pattern]' --lang ts src/ ```
``` grep(pattern="[search_term]", path="src/", include="*.ts") ```
``` background_output(task_id="[agent_1_id]") background_output(task_id="[agent_2_id]") ... ```
Mark phase-1 as completed after all results collected.
Mark phase-2 as in_progress.
Based on Phase 1 results, build:
```
``` [TARGET] ├── imports from: │ ├── module-a (types) │ └── module-b (utils) ├── imported by: │ ├── consumer-1.ts │ ├── consumer-2.ts │ └── consumer-3.ts └── used by: ├── handler.ts (direct call) └── service.ts (dependency injection) ```
| Zone | Risk Level | Files Affected | Test Coverage |
|---|---|---|---|
| Core | HIGH | 3 files | 85% covered |
| Consumers | MEDIUM | 8 files | 70% covered |
| Edge | LOW | 2 files | 50% covered |
Based on codemap:
Mark phase-2 as completed.
Mark phase-3 as in_progress.
```bash
cat package.json | jq '.scripts | keys[] | select(test("test"))'
ls -la pytest.ini pyproject.toml setup.cfg
ls -la *_test.go ```
``` // Find all tests related to target call_omo_agent( subagent_type="explore", run_in_background=false, // Need this synchronously prompt="Analyze test coverage for [TARGET]:
Based on test analysis:
| Coverage Level | Strategy |
|---|---|
| HIGH (>80%) | Run existing tests after each step |
| MEDIUM (50-80%) | Run tests + add safety assertions |
| LOW (<50%) | PAUSE: Propose adding tests first |
| NONE | BLOCK: Refuse aggressive refactoring |
If coverage is LOW or NONE, ask user:
``` Test coverage for [TARGET] is [LEVEL].
Risk Assessment: Refactoring without adequate tests is dangerous.
Options:
Which approach do you prefer? ```
```
After each refactoring step:
Mark phase-3 as completed.
Mark phase-4 as in_progress.
``` Task( subagent_type="plan", prompt="Create a detailed refactoring plan:
[User's original request]
[Insert codemap here]
[Insert verification plan here]
After receiving plan from Plan agent:
Convert Plan agent output into granular todos:
``` TodoWrite([ // Each step from the plan becomes a todo {"id": "refactor-1", "content": "Step 1: [description]", "status": "pending", "priority": "high"}, {"id": "verify-1", "content": "Verify Step 1: run tests", "status": "pending", "priority": "high"}, {"id": "refactor-2", "content": "Step 2: [description]", "status": "pending", "priority": "medium"}, {"id": "verify-2", "content": "Verify Step 2: run tests", "status": "pending", "priority": "medium"}, // ... continue for all steps ]) ```
Mark phase-4 as completed.
Mark phase-5 as in_progress.
For EACH refactoring step:
Use appropriate tool:
For Symbol Renames: ```typescript lsp_prepare_rename(filePath, line, character) // Validate rename is possible lsp_rename(filePath, line, character, newName) // Execute rename ```
For Pattern Transformations: ```bash // Preview first sg --pattern '[pattern]' --rewrite '[rewrite]' --lang ts path/to/file.ts
// If preview looks good, execute python3 scripts/ast_grep_helper.py replace '[pattern]' '[rewrite]' --lang ts path/to/file.ts --apply ```
For Structural Changes: ```typescript // Use Edit tool for precise changes edit(filePath, oldString, newString) ```
```typescript // 1. Check diagnostics lsp_diagnostics(filePath) // Must be clean or same as baseline
// 2. Run tests bash("bun test") // Or appropriate test command
// 3. Type check bash("tsc --noEmit") // Or appropriate type check ```
If ANY verification fails:
NEVER proceed to next step with broken tests.
After each logical group of changes:
```bash git add [changed-files] git commit -m "refactor(scope): description
[details of what was changed and why]" ```
Mark phase-5 as completed when all refactoring steps done.
Mark phase-6 as in_progress.
```bash
bun test # or npm test, pytest, go test, etc. ```
```bash
tsc --noEmit # or equivalent ```
```bash
eslint . # or equivalent ```
```bash
bun run build # or npm run build, etc. ```
```typescript // Check all changed files for (file of changedFiles) { lsp_diagnostics(file) // Must all be clean } ```
```markdown
All existing tests pass. No new errors introduced. ```
Mark phase-6 as completed.
sg --pattern ... --rewrite ... --lang ...)If any of these occur, STOP and consult user:
You already know these tools. Use them intelligently:
Leverage LSP tools for precision analysis. Key patterns:
Use `ast-grep` skill helper or `sg` CLI for structural transformations. Critical: Always preview first, review, then execute.
When you encounter deprecated methods/APIs during refactoring:
Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.
$ARGUMENTS `Team mode is enabled for this session. The rules below override Phase 4-6 above. Follow this protocol instead of the in-session step-by-step execution.
When invoking the Plan agent in Phase 4.1, append this additional requirement to the prompt:
``` 7. (REQUIRED when team mode is active) Output a Team Staffing Recommendation section with these fields — missing fields fail Phase 5.0:
Classification rules the plan agent must apply to each step:
Read the Team Staffing Recommendation from Phase 4. If any required field is missing, fail here and re-request the plan with the exact missing field names. Do not proceed with a partial plan.
Then choose the path:
Record the chosen path in the TodoWrite list.
Precondition checks (fail hard if any step fails):
Team spec (`~/.omo/teams/refactor-squad/config.json`):
```json { "name": "refactor-squad", "lead": { "kind": "subagent_type", "subagent_type": "sisyphus" }, "members": [ { "kind": "category", "category": "quick", "prompt": "You handle mechanical refactoring steps (LSP rename, extract variable, inline, simple move, signature change). Use LSP tools for correctness. Apply the task description's per-step instructions verbatim — no scope expansion. After edits, run lsp_diagnostics on touched files. Report via team_send_message(teamRunId=, to="lead", summary=, body=<lsp status + diff summary>) + team_task_update(status=completed). Never run tests — the external verifier handles that. Never git add, never --continue." }, { "kind": "category", "category": "quick", "prompt": "Same contract as peer quick worker." }, { "kind": "category", "category": "unspecified-low", "prompt": "You handle logic-preserving refactors that need reasoning (extract function, restructure conditional, pattern transformation, cross-file API change). Read the task description's plan step carefully. Use the ast-grep skill helper or sg CLI to preview structural rewrites first, review the preview, then execute. If the step is ambiguous or would require out-of-scope changes, STOP and send team_send_message(teamRunId=, to="lead", summary="UNCLEAR", body=) + team_task_update(status=pending). Same reporting contract as peer quick workers. Never run tests." }, { "kind": "category", "category": "unspecified-low", "prompt": "Same contract as peer unspecified-low worker." } ] } ```
Rationale for this composition:
Team lifecycle (one team, reused until Phase 6 cleanup):
Lead monitoring loop:
While any team task is `pending | claimed | in_progress`:
Proceed to Phase 6 only when every team task is `completed` AND every paired verifier task returned PASS.
If Phase 5 used the team path, dismantle `refactor-squad` BEFORE producing the 6.6 summary. Every exit path — success, escalation, abort — must cleanup; orphan teams poison the next session's precondition check.
The `~/.omo/teams/refactor-squad/config.json` declaration stays on disk; next session reuses it.
Append to the 6.6 summary a "Dispatch path" line and, when team path was used, team metrics (teamRunId, tasks created, verifier runs, team lifetime).