refactor
Targeted refactoring tool that enforces quality principles and manages code entropy.
Install
mkdir -p .claude/skills/refactor-cwijayasundara && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/17180" && unzip -o skill.zip -d .claude/skills/refactor-cwijayasundara && rm skill.zipInstalls to .claude/skills/refactor-cwijayasundara
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Refactor existing code for quality, performance, or maintainability. Enforces core quality principles with ratchet gate.Key capabilities
- →Refactor code in a specified file or directory
- →Perform whole-repository entropy scans
- →Auto-fix CLEANUP-class items during a sweep
- →Execute bulk mechanical transformations
- →Analyze code against core quality principles
- →Plan and execute changes one principle at a time
How it works
The skill analyzes a target against core quality principles, plans changes, and executes them one principle at a time, or performs a whole-repo entropy scan, or executes a bulk mechanical transform.
Inputs & outputs
When to use refactor
- →Refactor legacy code
- →Improve code maintainability
- →Run entropy scans
About this skill
Refactor Skill — Quality-Driven Code Improvement
Ultracode tip: A whole-repo
--sweepis a broad "scan many files, report the conclusion" task — run/effort ultracodebefore it for wider coverage. A targeted/refactor <path>is narrow and deterministic; leave ultracode off (/effort high) for those.
Usage
/refactor src/service/extraction.py
/refactor src/repository/
/refactor --sweep # whole-repo entropy scan (formerly /lint-drift)
/refactor --sweep --auto-fix # sweep + auto-commit CLEANUP-class items
/refactor --mechanical # bulk mechanical transform via specs/migrate/ (Bun Phase B)
Provide a file path or directory for a targeted refactor. Use --sweep for a whole-repo entropy scan that reports accumulated drift and routes findings back into the per-principle fix flow. Use --mechanical for a large pattern→pattern transform (port, framework swap, monorepo split) driven by specs/migrate/ mapping artifacts — not for principle-by-principle cleanup. The skill analyzes the target against core quality principles, plans the changes, and executes them one principle at a time (except --mechanical, which follows the migrate flow below).
Overview
Refactoring improves the internal structure of existing code without changing its observable behavior. No new features. No behavior changes. Every change must trace to a violation of the core quality principles.
For tiny cleanup that is obviously safe and local (for example one unused import, one typo in a comment, one lint-only change), use /vibe instead. Use /refactor when the change affects structure, module boundaries, tests, or multiple files.
Mechanical Migrate Mode (/refactor --mechanical)
For bulk faithful transforms (language port, framework upgrade call-sites, monorepo split) where the behaviour oracle is the existing suite — not a new product feature.
- Ensure
specs/migrate/exists. If missing, copy templates from.claude/templates/migrate/(README.md,MAPPING.md,CONSTRAINTS.tsv,CANARY.md) intospecs/migrate/. - Draft or load
MAPPING.md(and optionalCONSTRAINTS.tsv). Do not fan out code until the mapping is specific enough that two independent readers would make the same mechanical choice. - Adversarially review the mapping (not the whole tree): spawn two independent
code-reviewerinstances onspecs/migrate/MAPPING.md(+CONSTRAINTS.tsvif present) with fresh context; merge withmerge-review-verdicts.js --policy unionif both produce verdict JSON, or require a human ack for high-risk ports. Fix mapping conflicts before any production edit. - Canary always: apply the transform to 3 files (or the smallest representative sample), run tests/lint/types, record results in
specs/migrate/CANARY.md. A canary failure revises the mapping — do not extend a broken pattern. - Fan-out only after canary pass, under file ownership / ownership map when present. Prefer
fix-from-diagnosticswhen the fan-out produces a large type/lint wall. - Oracle: G31 still applies — do not delete or skip tests to green the suite. Prefer dual adversarial review on large diffs (
review-tier.js). - Semantic divergence: instruct every
code-reviewerspawn to apply.claude/skills/code-gen/references/semantic-divergence.md(assert side effects, rounding, bounds, Drop/defer, placeholder constants). Record open hazards inMAPPING.md→ Semantic divergence watchlist. - Commits: keep mapping/canary commits separate from bulk code when practical (
keeping-refactors-purewhen behaviour is unchanged). Prefer review-attributed subjects after dual review:git commit -m "$(node .claude/scripts/review-commit-msg.js --subject 'port: canary batch' --from-audit specs/reviews/adversarial-review-audit.json)"
This mode is not /build or /sprint. If the work needs new product behaviour, use /change or /feature instead.
Drift Sweep Mode (/refactor --sweep)
/refactor <path> fixes a targeted area. /refactor --sweep runs the whole-repo entropy scan (this absorbs the former /lint-drift skill): it reports accumulated drift and routes the findings back into the per-principle fix flow below. Entropy control for agent-generated code — as agents replicate patterns, drift accumulates.
What the sweep scans:
- Structural drift (from
code-graph.json, not grep): orphan/dead files (fan_in == 0), layer-violation import directions, unstable hubs, cycles. Run/code-mapfirst if the graph is missing or stale (stale =.claude/state/graph-dirty.jsonlnon-empty — thegraph-refreshStop hook normally drains it); prefer the graph over grep. Always grep for dynamic references (getattr, registries,importlib) before declaring anything dead. - Cross-file duplicate logic: near-identical function bodies across 3+ files → extract a shared utility. This is the sweep's unique signal (neither
code-mapnor a targeted refactor finds it). - Principle violations: file/function length, missing types, bare excepts, hardcoded config. Thresholds are single-sourced in
code-gen/SKILL.md(do not restate them); the length/type cases are also enforced live by the hooks — the sweep catches what predates them. - Test-quality drift: assert-nothing tests, mocked business logic.
Sweep workflow:
- Refresh
code-graph.json(/code-map) if missing or stale. - Scan files changed since the last sweep (marker
.claude/state/last-drift-scan.txt, a commit SHA); full scan if no marker. - Write
specs/reviews/drift-report.md— category,file:line, suggested fix, severity (CLEANUP / REFACTOR / DEBT). - Route REFACTOR-class items through Steps 1–8 below (the ratchet-gated fix). With
--auto-fix, CLEANUP-class items may be auto-committed — they must pass the full ratchet gate. - Record the new scan SHA to
.claude/state/last-drift-scan.txt.
When to sweep: after every ~5 /auto iterations, before a release, or when learned-rules.md grows past ~10 rules (pattern-accumulation signal). Do not refactor code outside the current change's scope without recording it as drift first.
Steps
Step 1 — Read Quality Principles
Read .claude/skills/code-gen/SKILL.md in full. Its core quality principles are the refactoring standard. Every change planned in Step 4 must cite a specific principle.
Step 2 — Analyze Current State
Context-first (Iron Law) — REQUIRED when specs/brownfield/code-graph.json exists and is not a placeholder. Before broad source reads or unconstrained search over the target:
node .claude/scripts/context-pack.js --diff --budget 1600 "<refactor goal or target path>"
# blast radius for renames/moves (when you have a node id or path):
node .claude/skills/code-map/scripts/code_wiki.js query --graph specs/brownfield/code-graph.json --callers <id>
Read only pack read_next ranges (and skeletons + Read(offset, limit) for god files). Use task_map and caller results as the impact seed. If confidence is low / no_match, one narrow rg then re-pack — do not multi-file explore. If the graph is missing on a non-trivial codebase, recommend /brownfield before broad refactoring.
If maps exist and pack confidence is low, optionally read architecture-map.md, risk-map.md, or change-strategy.md — do not front-load every essay when the pack is high-confidence. Locate symbols via pack ranges first, then symbol-map.md (Lstart-Lend); for files flagged in skeletons/, read the .skel.md and then only the relevant symbol slice with Read(offset, limit) instead of the whole file.
Coverage preflight — REQUIRED SUB-SKILL: checking-coverage-before-change for every symbol in the target path before the first edit. COVERED symbols give you the regression oracle to run after each step; UNCOVERED symbols route to pinning-down-behavior (or sprouting-instead-of-editing) before any in-place edit.
Migration preflight — REQUIRED SUB-SKILL: checking-migration-safety if the refactor touches ORM models or schema files (e.g. renaming a model field). A behavior-preserving refactor that requires a schema migration is two deployables, not one commit.
Canvas sync preflight: if specs/design/reasons-canvas.md exists and the refactor moves, renames, splits, deletes, or creates governed source files, update the Canvas Operations and Governs sections before the refactor is considered complete. After the file movement/change, run npm run canvas-sync; a mismatch is a hard-block because a refactor must not leave the living design pointing at stale paths.
For each file in the target path:
- Architecture compliance: does the file import from a layer above it? (see layering rules in
code-gen/references/architecture.md) - Function lengths: count lines in each function. Flag any over 30 lines (the pre-write-gate hook limit).
- Type coverage: identify any
any(TypeScript) or missing type hints (Python). Count unannotated parameters and return types. - Test coverage baseline: run the test suite and record current pass/fail counts and coverage percentage.
- Dead code: identify unused imports, unreachable branches, commented-out code.
- Documentation style: identify comments that restate the code rather than explaining non-obvious decisions.
Record findings in a structured list before proceeding.
Step 3 — Identify Violations
Map each finding from Step 2 to one of the core quality principles:
- Small Modules — file exceeds 300 lines (block) or 200 lines (warning).
- Static Typing —
any, missing annotations, untyped domain concepts. - Functions Under 30 Lines — function body exceeds 30 lines.
- Explicit Error Handling — bare
except, untyped catches, swallowed errors. - No Dead Code — unused imports, commented-out code, unreachable branches.
- Self-Documenting — comments that restate what the code does, not why.
Content truncated.
When not to use it
- →When the work needs new product behavior
- →For tiny cleanup that is obviously safe and local
- →When the change affects structure, module boundaries, tests, or multiple files
Limitations
- →No new features are introduced
- →No behavior changes are made
- →Every change must trace to a violation of core quality principles
How it compares
This skill systematically applies core quality principles or predefined mechanical transformations, unlike manual refactoring which may lack consistent application of standards.
Compared to similar skills
refactor side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| refactor (this skill) | 0 | 1mo | No flags | Intermediate |
| software-architecture | 333 | 6mo | No flags | Intermediate |
| oracle | 17 | 3mo | Review | Intermediate |
| clojure-write | 16 | 3mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by cwijayasundara
View all by cwijayasundara →You might also like
software-architecture
davila7
Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development.
oracle
openclaw
Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns).
clojure-write
metabase
Guide Clojure and ClojureScript development using REPL-driven workflow, coding conventions, and best practices. Use when writing, developing, or refactoring Clojure/ClojureScript code.
add-uint-support
pytorch
Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.
cpp-pro
sickn33
Write idiomatic C++ code with modern features, RAII, smart pointers, and STL algorithms. Handles templates, move semantics, and performance optimization. Use PROACTIVELY for C++ refactoring, memory safety, or complex C++ patterns.
python-patterns
affaan-m
Pythonic 惯用法、PEP 8 标准、类型提示以及构建健壮、高效、可维护的 Python 应用程序的最佳实践。