with one click
refactoring
// [Code Quality] Use when you need restructure code without changing behavior using extract method, extract class, rename, move, and inline patterns.
// [Code Quality] Use when you need restructure code without changing behavior using extract method, extract class, rename, move, and inline patterns.
[HINT] Download the complete skill directory including SKILL.md and all related files
| name | refactoring |
| version | 2.2.0 |
| description | [Code Quality] Use when you need restructure code without changing behavior using extract method, extract class, rename, move, and inline patterns. |
Goal: Restructure code without changing behavior using extract, move, and simplify patterns.
Workflow:
Key Rules:
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
file:line evidenceMANDATORY IMPORTANT MUST ATTENTION declare Confidence: X% with evidence list + file:line proof for EVERY claim.
95%+ recommend freely | 80-94% with caveats | 60-79% list unknowns | <60% STOP — gather more evidence.
Breaking changes (removing classes, changing interfaces) require 95%+ confidence with full cross-service trace.
Expert code restructuring agent. Focuses on structural changes that improve code quality without modifying behavior.
| Pattern | When to Use | Example |
|---|---|---|
| Extract Method | Long method, duplicated code | Move logic to private method |
| Extract Class | Class has multiple responsibilities | Create Helper, Service, or Strategy class |
| Extract Interface | Need abstraction for testing/DI | Create I{ClassName} interface |
| Extract Expression | Complex inline expression | Move to Entity static expression |
| Extract Validator | Repeated validation logic | Create validator extension method |
| Pattern | When to Use | Example |
|---|---|---|
| Move Method | Method belongs to different class | Move from Handler to Helper/Entity |
| Move to Extension | Reusable repository logic | Create {Entity}RepositoryExtensions |
| Move to DTO | Mapping logic in handler | Use project DTO base .MapToEntity() (see docs/project-reference/backend-patterns-reference.md) |
| Move to Entity | Business logic in handler | Add instance method or static expression |
| Pattern | When to Use | Example |
|---|---|---|
| Inline Variable | Temporary variable used once | Remove intermediate variable |
| Inline Method | Method body is obvious | Replace call with body |
| Replace Conditional | Complex if/switch | Use Strategy pattern or expression |
| Introduce Parameter Obj | Method has many parameters | Create Command/Query DTO |
.ai/workspace/analysis/{refactoring-name}.analysis.md. Re-read before planning.Document refactoring plan:
## Refactoring Plan
**Target**: [file:line_number]
**Type**: [Extract Method | Move to Extension | etc.]
**Reason**: [Why this refactoring improves code]
### Changes
1. [ ] Create/modify [file]
2. [ ] Update usages in [files]
3. [ ] Run tests
### Risks
- [Potential issues]
// BEFORE: Logic in handler
protected override async Task<Result> HandleAsync(Command req, CancellationToken ct)
{
var isValid = entity.Status == Status.Active &&
entity.User?.IsActive == true &&
!entity.IsDeleted;
if (!isValid) throw new Exception();
}
// AFTER: Extracted to entity static expression
// In Entity.cs
public static Expression<Func<Entity, bool>> IsActiveExpr()
=> e => e.Status == Status.Active &&
e.User != null && e.User.IsActive &&
!e.IsDeleted;
// In Handler
var entity = await repository.FirstOrDefaultAsync(Entity.IsActiveExpr(), ct)
.EnsureFound("Entity not active");
// BEFORE: Reused logic in multiple handlers
var employee = await repo.FirstOrDefaultAsync(Employee.UniqueExpr(userId, companyId), ct)
?? await CreateEmployeeAsync(userId, companyId, ct);
// AFTER: Extracted to Helper
// In EmployeeHelper.cs
public async Task<Employee> GetOrCreateEmployeeAsync(string userId, string companyId, CancellationToken ct)
{
return await repo.FirstOrDefaultAsync(Employee.UniqueExpr(userId, companyId), ct)
?? await CreateEmployeeAsync(userId, companyId, ct);
}
// BEFORE: Query logic in handler
var employees = await repo.GetAllAsync(
e => e.CompanyId == companyId && e.Status == Status.Active && e.DepartmentIds.Contains(deptId), ct);
// AFTER: Extracted to extension
// In EmployeeRepositoryExtensions.cs
public static async Task<List<Employee>> GetActiveByDepartmentAsync(
this I{Service}RootRepository<Employee> repo, string companyId, string deptId, CancellationToken ct)
{
return await repo.GetAllAsync(
Employee.OfCompanyExpr(companyId)
.AndAlso(Employee.IsActiveExpr())
.AndAlso(e => e.DepartmentIds.Contains(deptId)), ct);
}
// BEFORE: Mapping in handler
var config = new AuthConfig
{
ClientId = req.Dto.ClientId,
Secret = encryptService.Encrypt(req.Dto.Secret)
};
// AFTER: DTO owns mapping
// In AuthConfigDto.cs : DtoBase<AuthConfig> // project DTO base class (see docs/project-reference/backend-patterns-reference.md)
public override AuthConfig MapToObject() => new AuthConfig
{
ClientId = ClientId,
Secret = Secret // Handler applies encryption
};
// In Handler
var config = req.Dto.MapToObject()
.With(c => c.Secret = encryptService.Encrypt(c.Secret));
[IMPORTANT] Database Performance Protocol (MANDATORY):
- Paging Required — ALL list/collection queries MUST ATTENTION use pagination. NEVER load all records into memory. Verify: no unbounded
GetAll(),ToList(), orFind()withoutSkip/Takeor cursor-based paging.- Index Required — ALL query filter fields, foreign keys, and sort columns MUST ATTENTION have database indexes configured. Verify: entity expressions match index field order, database collections have index management methods, migrations include indexes for WHERE/JOIN/ORDER BY columns.
When extracting expressions or moving queries, verify index coverage:
Before any refactoring:
Confidence: X% with evidence list?If ANY checklist item incomplete → STOP. State "Insufficient evidence to proceed."
⚠️ MUST ATTENTION READ: CLAUDE.md "Code Responsibility Hierarchy" for the Entity/Model > Service > Component layering rule. When refactoring, verify logic is in the LOWEST appropriate layer.
⚠️ MUST ATTENTION READ: CLAUDE.md "Component HTML Template Standard (BEM Classes)" and docs/project-reference/scss-styling-guide.md for BEM class requirements and host/wrapper styling patterns. When refactoring components, ensure all HTML elements have proper BEM classes.
Run
python .claude/scripts/code_graph connections <file> --jsonon refactored files to find all consumers needing updates.
If .code-graph/graph.db exists, enhance analysis with structural queries:
python .claude/scripts/code_graph query callers_of <function> --jsonpython .claude/scripts/code_graph query importers_of <module> --jsonpython .claude/scripts/code_graph batch-query file1 file2 --jsonSee
<!-- SYNC:graph-assisted-investigation -->block above for graph query patterns.
When graph DB is available, BEFORE refactoring, trace to verify all consumers:
python .claude/scripts/code_graph trace <file-to-refactor> --direction downstream --json — all downstream consumers that depend on this codepython .claude/scripts/code_graph trace <file-to-refactor> --direction both --json — full picture: callers + consumerscode-simplifiercode-reviewMANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS: If you are NOT already in a workflow, you MUST ATTENTION use
AskUserQuestionto ask the user. Do NOT judge task complexity or decide this is "simple enough to skip" — the user decides whether to use a workflow, not you:
- Activate
refactorworkflow (Recommended) — scout → investigate → plan → code → review → sre-review → test → docs- Execute
/refactoringdirectly — run this skill standalone
Completion ≠ Correctness. Before reporting ANY work done, prove it:
- Grep every removed name. Extraction/rename/delete touched N files? Grep confirms 0 dangling refs across ALL file types.
- Ask WHY before changing. Existing values are intentional until proven otherwise. No "fix" without traced rationale.
- Verify ALL outputs. One build passing ≠ all builds passing. Check every affected stack.
- Evaluate pattern fit. Copying nearby code? Verify preconditions match — same scope, lifetime, base class, constraints.
- New artifact = wired artifact. Created something? Prove it's registered, imported, and reachable by all consumers.
[IMPORTANT] Use
TaskCreateto break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
docs/project-reference/domain-entities-reference.md — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models) (read directly when relevant; do not rely on hook-injected conversation text)Graph-Assisted Investigation — MANDATORY when
.code-graph/graph.dbexists.HARD-GATE: MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files →
trace --direction bothreveals full system flow → Grep verifies details
Task Minimum Graph Action Investigation/Scout trace --direction bothon 2-3 entry filesFix/Debug callers_ofon buggy function +tests_forFeature/Enhancement connectionson files to be modifiedCode Review tests_foron changed functionsBlast Radius trace --direction downstreamCLI:
python .claude/scripts/code_graph {command} --json. Use--node-mode filefirst (10-30x less noise), then--node-mode functionfor detail.
Nested Task Expansion Contract — For workflow-step invocation, the
[Workflow] ...row is only a parent container; the child skill still creates visible phase tasks.
- Call
TaskListfirst. If a matching active parent workflow row exists, setnested=trueand recordparentTaskId; otherwise run standalone.- Create one task per declared phase before phase work. When nested, prefix subjects
[N.M] $skill-name — phase.- When nested, link the parent with
TaskUpdate(parentTaskId, addBlockedBy: [childIds]).- Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
- Mark exactly one child
in_progressbefore work andcompletedimmediately after evidence is written.- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until:
TaskListdone, child phases created, parent linked when nested, first child markedin_progress.
Project Reference Docs Gate — Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
- Identify scope: file types, domain area, and operation.
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookupdocs-index-reference.md; reviewcode-review-rules.md; backend/CQRS/APIbackend-patterns-reference.md; domain/entitydomain-entities-reference.md; frontend/UIfrontend-patterns-reference.md; styles/designscss-styling-guide.md+design-system/README.md; integration testsintegration-test-reference.md; E2Ee2e-test-reference.md; feature docs/specsfeature-docs-reference.md; architecture/new areaproject-structure-reference.md.- Read every required doc that exists; skip absent docs as not applicable. Do not trust conversation text such as
[Injected: <path>]as proof that the current context contains the doc.- Before target work, state:
Reference docs read: ... | Missing/not applicable: ....Blocked until: scope evaluated, required docs checked/read,
lessons.mdconfirmed, citation emitted.
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
Understand Code First — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
- Search 3+ similar patterns (
grep/glob) — citefile:lineevidence- Read existing files in target area — understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --jsonwhen.code-graph/graph.dbexists- Map dependencies via
connectionsorcallers_of— know what depends on your target- Write investigation to
.ai/workspace/analysis/for non-trivial tasks (3+ files)- Re-read analysis file before implementing — never work from memory alone
- NEVER invent new patterns when existing ones work — match exactly or document deviation
BLOCKED until:
- [ ]Read target files- [ ]Grep 3+ patterns- [ ]Graph trace (if graph.db exists)- [ ]Assumptions verified with evidence
Evidence-Based Reasoning — Speculation is FORBIDDEN. Every claim needs proof.
- Cite
file:line, grep results, or framework docs for EVERY claim- Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
- Cross-service validation required for architectural changes
- "I don't have enough evidence" is valid and expected output
BLOCKED until:
- [ ]Evidence file path (file:line)- [ ]Grep search performed- [ ]3+ similar patterns found- [ ]Confidence level statedForbidden without proof: "obviously", "I think", "should be", "probably", "this is because" If incomplete → output:
"Insufficient evidence. Verified: [...]. Not verified: [...]."
Design Patterns Quality — Priority checks for every code change:
- DRY via OOP: Identify classes/modules with the same purpose, naming pattern, or lifecycle. Apply your knowledge of the project's language/framework to determine the idiomatic abstraction (base class, mixin, trait, protocol, decorator). 3+ similar patterns → extract to shared abstraction.
- Right Responsibility: Logic in LOWEST layer (Entity > Domain Service > Application Service > Controller). Never business logic in controllers.
- SOLID: Single responsibility (one reason to change). Open-closed (extend, don't modify). Liskov (subtypes substitutable). Interface segregation (small interfaces). Dependency inversion (depend on abstractions).
- After extraction/move/rename: Grep ENTIRE scope for dangling references. Zero tolerance.
- YAGNI gate: NEVER recommend patterns unless 3+ occurrences exist. Don't extract for hypothetical future use.
Anti-patterns to flag: God Object, Copy-Paste inheritance, Circular Dependency, Leaky Abstraction.
Serial Attention for Design Quality — DO NOT scan all quality concerns simultaneously. Split attention misses violations that focused passes catch.
- Identify applicable dimensions — Based on the code's language, domain, and patterns, determine which quality dimensions apply: DRY, SOLID principles (SRP/OCP/LSP/ISP/DIP), OOP idioms, cohesion/coupling, GRASP, Law of Demeter, CQRS invariants, etc. Your list is NOT fixed — derive from what the code actually does.
- One focused pass per dimension — Dedicate single-focus attention to EACH dimension in sequence. Do NOT mix concerns across passes.
- Threshold: 3+ similar patterns = MANDATORY extraction — Not optional suggestion. Flag as mandatory structural fix requiring action.
- 2+ violations of same kind = structural finding — Report as "pattern problem" needing architectural resolution, not a list of individual instances.
AI Mistake Prevention — Failure modes to avoid on every task:
Check downstream references before deleting. Deleting components causes documentation and code staleness cascades. Map all referencing files before removal. Verify AI-generated content against actual code. AI hallucinates APIs, class names, and method signatures. Always grep to confirm existence before documenting or referencing. Trace full dependency chain after edits. Changing a definition misses downstream variables and consumers derived from it. Always trace the full chain. Trace ALL code paths when verifying correctness. Confirming code exists is not confirming it executes. Always trace early exits, error branches, and conditional skips — not just happy path. When debugging, ask "whose responsibility?" before fixing. Trace whether bug is in caller (wrong data) or callee (wrong handling). Fix at responsible layer — never patch symptom site. Assume existing values are intentional — ask WHY before changing. Before changing any constant, limit, flag, or pattern: read comments, check git blame, examine surrounding code. Verify ALL affected outputs, not just the first. Changes touching multiple stacks require verifying EVERY output. One green check is not all green checks. Holistic-first debugging — resist nearest-attention trap. When investigating any failure, list EVERY precondition first (config, env vars, DB names, endpoints, DI registrations, data preconditions), then verify each against evidence before forming any code-layer hypothesis. Surgical changes — apply the diff test. Bug fix: every changed line must trace directly to the bug. Don't restyle or improve adjacent code. Enhancement task: implement improvements AND announce them explicitly. Surface ambiguity before coding — don't pick silently. If request has multiple interpretations, present each with effort estimate and ask. Never assume all-records, file-based, or more complex path.
IMPORTANT MUST ATTENTION search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
IMPORTANT MUST ATTENTION cite file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
IMPORTANT MUST ATTENTION check DRY via OOP, right responsibility layer, SOLID. Grep for dangling refs after moves.
IMPORTANT MUST ATTENTION run at least ONE graph command on key files when graph.db exists. Pattern: grep → trace → verify.
MUST ATTENTION apply critical thinking — every claim needs traced proof, confidence >80% to act. Anti-hallucination: never present guess as fact.
MUST ATTENTION apply AI mistake prevention — holistic-first debugging, fix at responsible layer, surface ambiguity before coding, re-read files after compaction.
Reference docs read: ....lessons.md; project conventions override generic defaults.[N.M] $skill-name — phase prefixes and one-in_progress discipline.IMPORTANT MUST ATTENTION break work into small todo tasks using TaskCreate BEFORE starting
IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code
IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act)
IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
MANDATORY IMPORTANT MUST ATTENTION READ the following files before starting:
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using TaskCreate.