refactor · diff
git:20260702.8f6da63 to git:20260719.4ee8666
74 added, 427 removed. Audit A to A.
---
name: refactor
description: "Restructures existing code without changing its behavior — maps callers and test coverage, adds characterization tests where coverage is thin, then applies the change in small steps verified against the full test suite after each one. Use when the user wants to refactor, extract a method or class, simplify logic, reduce duplication, improve naming, restructure modules, or pay down technical debt in code that already works. Not for adding new functionality (use implement-feature) or fixing broken behavior (use fix-bug)."
disable-model-invocation: false
argument-hint: "<refactoring_description> [--scope file|module|project] [--interactive]"
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebFetch, AskUserQuestion
hooks:
Stop:
- hooks:
- type: agent
- prompt: "Verify refactoring is safe and complete:\n\n1. **Behavior preserved**: Run the full test suite using the test command from Phase 0. All tests must pass — the same tests that passed before the refactoring must still pass.\n2. **No regressions**: Run linter and type checker. No new errors allowed.\n3. **Characterization tests**: If characterization tests were added in Phase 3, verify they still pass.\n4. **Clean diff**: Review git diff to confirm only intentional refactoring changes exist — no accidental behavior changes, debug code, or commented-out code.\n\nIf any verification fails, report it clearly and return decision: block with reason. Only allow stopping when the refactoring is verified safe.\n\nUse test commands discovered in Phase 0. If not available, discover them now from CLAUDE.md or project files."
+ prompt: "Run the Phase 4 Quality Gates Checklist from SKILL.md against the current diff and the test/lint/type-check commands discovered in Phase 0 (fall back to CLAUDE.md or project files if Phase 0 wasn't run). If any item fails, return decision: block with the specific failing item named. Only allow stopping when every item passes."
timeout: 180
---
# Refactor
Refactor code safely using characterization tests, incremental changes, and continuous verification. Every change preserves existing behavior while improving code structure, readability, and maintainability.
## Refactoring Goal
$ARGUMENTS
## Core Principle: Behavior Preservation
- **CRITICAL**: Refactoring changes code structure WITHOUT changing behavior. Every step must be verified against existing tests. If tests break, the refactoring introduced a bug — revert and retry.
+ Refactoring changes code structure WITHOUT changing behavior. Every step must be verified against existing tests. If tests break, the refactoring introduced a bug — revert and retry.
## Anti-Hallucination Guidelines
- 1. **Read before changing** — Never refactor code that has not been read and understood. Understand all callers and dependencies first.
- 2. **Test before and after** — Run the full test suite before starting. Run it again after every incremental change. The results must match.
- 3. **Characterization tests first** — If test coverage is insufficient for the target code, write characterization tests that capture current behavior BEFORE refactoring.
- 4. **Incremental changes** — Make one small, verifiable change at a time. Never combine multiple refactoring steps into a single edit.
- 5. **No feature changes** — Do not add features, fix bugs, or change behavior during refactoring. These are separate tasks.
- 6. **Reference real code** — Never make claims about code structure that has not been verified by reading the actual files.
- 7. **Prefer deletion over addition** — The best refactoring step is usually the one that removes duplicated or dead code, not the one that adds a new layer around it. When several call sites share the same logic, consolidate it into one place and delete the copies rather than introducing a new abstraction that wraps them.
- 8. **Never trim the floor** — Simplifying structure must not simplify away a validation check, an error/data-loss path, a security control, or an accessibility branch. If a step would drop one, it is a behavior change, not a refactor — stop and re-scope it as a separate change.
+ 1. **Read before changing** — understand all callers and dependencies first.
+ 2. **Test before and after** — full suite before starting, and again after every incremental change. Results must match.
+ 3. **Characterization tests first** — where coverage is thin, capture current behavior in tests before restructuring.
+ 4. **Incremental changes** — one small, verifiable change at a time. Never combine steps into a single edit.
+ 5. **No feature changes** — refactoring doesn't add features, fix bugs, or change behavior; those are separate tasks (`implement-feature`, `fix-bug`). Phase 0's scope gate below is where this gets enforced, not just stated.
+ 6. **Reference real code** — never claim a structure you haven't verified by reading the actual files.
+ 7. **Prefer deletion over addition** — when several call sites share logic, consolidate it into one place and delete the copies, rather than wrapping them in a new abstraction.
+ 8. **Never trim the floor** — simplifying structure must not drop a validation check, an error/data-loss path, a security control, or an accessibility branch. If a step would drop one, it's a behavior change, not a refactor — stop and re-scope it separately.
## Quality Gates
- This skill includes automatic refactoring verification before completion:
-
- ### Safety Verification (Stop Hook)
-
- When attempting to stop working, an automated verification agent runs to ensure the refactoring is safe:
-
- **Verification Steps:**
- 1. **Behavior preserved**: Full test suite passes (same results as before refactoring)
- 2. **No regressions**: Linter and type checker report no new errors
- 3. **Characterization tests**: Any tests added to capture behavior still pass
- 4. **Clean diff**: Only intentional structural changes exist
-
- **Behavior:**
- - ✅ **All verifications pass**: Refactoring marked complete
- - ❌ **Any test fails**: Completion blocked, Claude reverts or fixes the breaking change
- - ⚠️ **New lint/type errors**: Completion blocked until resolved
-
- **Example blocked completion:**
- ```
- ⚠️ Refactoring verification failed:
-
- Tests: ❌ FAILED (2 tests failing)
- - test_calculate_total: Expected 150.0, got 150
- - test_format_output: AssertionError: output format changed
-
- Lint: ✅ PASSED
- Type Check: ✅ PASSED
-
- 🔧 Refactoring introduced behavior changes. Revert the last change and retry
- with a smaller step.
- ```
+ A Stop hook re-runs the Phase 4 Quality Gates Checklist automatically and blocks completion if any item fails — see the hook prompt above for the exact wording.
## Task Management
- This skill uses Claude Code's Task Management System for strict sequential dependency tracking through the refactoring workflow.
+ Whether the ceremony below (formal task chain, subagent fan-out) is worth it depends on blast radius, not on whether the skill fired.
- **When to Use Tasks:**
- - Multi-step refactoring across files or modules
- - Extract method/class operations requiring dependency analysis
- - Large-scale restructuring with many callers
- - Work requiring progress tracking across sessions
+ The Phase 0 scope gate below always runs, even on the skip path — it's a five-second scan of the request, not ceremony.
- **When to Skip Tasks:**
- - Simple rename (single variable/function)
- - Trivial formatting or style fix
+ **Skip the task chain** — grep the callers yourself, run the existing tests, make the change, run tests again; done:
+ - Single-variable/function rename
+ - Formatting or style-only fix
- Single-line simplification
-
- **Task Structure:**
- Refactoring creates a strict sequential chain where each phase must complete before the next can start, ensuring characterization tests exist before any structural changes begin.
-
- ## Implementation Workflow
-
- **Task tracking replaces TodoWrite.** Create task chain at start, update as completing each phase.
-
- ### Phase 0: Project Discovery (REQUIRED)
-
- **Step 0.1: Create Task Dependency Chain**
-
- Before refactoring, create the strict sequential task structure:
-
- ```
- TaskCreate:
- subject: "Phase 0: Discover project workflow"
- description: "Identify test, lint, type-check commands from CLAUDE.md and task runners"
- activeForm: "Discovering project workflow"
-
- TaskCreate:
- subject: "Phase 1: Analyze refactoring scope"
- description: "Map dependencies, callers, and test coverage for target code"
- activeForm: "Analyzing refactoring scope"
-
- TaskCreate:
- subject: "Phase 2: Write characterization tests"
- description: "Ensure sufficient test coverage before making structural changes"
- activeForm: "Writing characterization tests"
-
- TaskCreate:
- subject: "Phase 3: Incremental refactoring"
- description: "Apply refactoring in small verified steps"
- activeForm: "Refactoring incrementally"
-
- TaskCreate:
- subject: "Phase 4: Final verification"
- description: "Run full test suite, lint, type-check — confirm behavior preserved"
- activeForm: "Verifying refactoring safety"
-
- TaskCreate:
- subject: "Phase 5: Final commit"
- description: "Create conventional commit with refactoring summary"
- activeForm: "Creating final commit"
-
- # Set up strict sequential chain
- TaskUpdate: { taskId: "2", addBlockedBy: ["1"] }
- TaskUpdate: { taskId: "3", addBlockedBy: ["2"] }
- TaskUpdate: { taskId: "4", addBlockedBy: ["3"] }
- TaskUpdate: { taskId: "5", addBlockedBy: ["4"] }
- TaskUpdate: { taskId: "6", addBlockedBy: ["5"] }
-
- # Start first task
- TaskUpdate: { taskId: "1", status: "in_progress" }
- ```
-
- **Step 0.2: Discover Project Workflow**
+ - Any single-file refactor (extract method, inline variable, simplify conditional) where one Grep enumerates every caller
- Use Haiku-powered Explore agent for token-efficient discovery:
+ **Use the full task chain (Phase 0-6 below)** when:
+ - The refactoring spans multiple files
+ - It's an extract/move-class operation, or anything needing a dependency-graph analysis
+ - The caller list isn't obvious from a single grep
+ - Progress needs to be tracked across sessions
- ```
- Use Task tool with Explore agent:
- - prompt: "Discover the development workflow for this project:
- 1. Read CLAUDE.md if it exists - extract testing and quality conventions
- 2. Check for task runners: Makefile, justfile, package.json scripts, pyproject.toml scripts
- 3. Identify the test command (e.g., make test, just test, npm test, pytest, bun test)
- 4. Identify how to run a single test file or specific test
- 5. Identify the lint command (e.g., make lint, npm run lint, ruff check)
- 6. Identify the type-check command if applicable (e.g., pyright, tsc, mypy)
- 7. Note any pre-commit hooks or quality gates
- 8. Check for code coverage tooling (e.g., pytest --cov, nyc, c8)
- Return a structured summary of all available commands."
- - subagent_type: "Explore"
- - model: "haiku" # Token-efficient for discovery
- ```
+ **Task structure:** a strict sequential chain — each phase blocked on the previous — so characterization tests exist before any structural change begins. `TaskCreate` returns the real task ID to use in `addBlockedBy`; don't hardcode literal IDs like `1`-`6`, other tasks may already exist in the session. After finishing each phase, mark its task `completed` and run `TaskList` to confirm the next one unblocked — this applies at the end of every phase below. Full `TaskCreate`/`TaskUpdate` templates and the Explore-agent prompts for Phase 0 and Phase 1 are in [references/task-chain.md](references/task-chain.md) — load it when actually running the full chain.
- Store discovered commands for use in later phases.
+ **Portability:** no `Task`/`TaskCreate` tools available? Drop the task chain and subagent fan-out — work through Phase 0-5 yourself, in order. The sequencing (characterization tests before structural change) is what matters, not the tracking mechanism.
- **Step 0.3: Run Baseline Tests**
+ ## Implementation Workflow
- **CRITICAL**: Run the full test suite BEFORE making any changes. Record the results as the baseline. Every subsequent test run must match or exceed this baseline.
+ ### Phase 0: Scope Gate + Project Discovery
- ```bash
- # Run full test suite and record results
- [DISCOVERED_TEST_COMMAND]
- ```
+ **Step 0a — Mixed-scope gate (blocking, do this before anything else, no exceptions):**
- If tests already fail before refactoring, document the pre-existing failures. These are not caused by the refactoring and should remain unchanged (same tests fail with same errors).
+ 1. Read the request for anything that isn't a pure structural change to existing behavior — a new option, a new endpoint, a bug fix, "while you're in there, also add...". A rename/extract/move/inline/simplify/dedupe is refactor scope; anything that changes what the code *does* for a caller is not.
+ 2. If the request is mixed-scope, do not write, edit, or commit any code for the behavior-changing half — not as a draft, not because "it's small anyway."
+ 3. If the split is unambiguous, proceed with the refactor half only and skip to Step 0b.
+ 4. If it's genuinely unclear which half the user wants (e.g. the request could be read as "rename only" or "rename plus feature, your call"), use `AskUserQuestion` to ask before writing any code. Don't guess.
+ 5. Whichever path you took, the Phase 6 summary MUST name the deferred behavior-changing piece by name and point to `implement-feature` (or `fix-bug`). This is checked against the actual final message sent to the user, not against intent recorded earlier in the run — a run that does the refactor correctly but never says what it skipped has not passed this gate.
- **Step 0.4: Complete Phase 0**
+ No mixed scope detected → proceed straight to Step 0b.
- ```
- TaskUpdate: { taskId: "1", status: "completed" }
- TaskList # Check that Task 2 is now unblocked
- ```
+ **Step 0b — Project discovery:** discover the project's test/lint/type-check commands (CLAUDE.md, Makefile/justfile/package.json/pyproject.toml — an Explore/Haiku agent works well here for wider projects, prompt in `references/task-chain.md`). Run the full test suite and record the baseline before touching any code. Pre-existing failures aren't yours to fix — just don't let the refactoring add new ones.
### Phase 1: Scope Analysis
- **Goal**: Understand the full impact of the refactoring before touching any code.
-
- **Step 1.1: Start Phase 1**
-
- ```
- TaskUpdate: { taskId: "2", status: "in_progress" }
- ```
-
- **Step 1.2: Parallel Scope Analysis**
-
- Spawn two Explore agents in parallel to map the refactoring scope:
-
- ```
- Agent 1 - Dependency & Caller Analysis (Explore, Haiku):
- prompt: "Analyze dependencies and callers for the refactoring target:
-
- Refactoring target: [DESCRIBE TARGET CODE]
-
- 1. Read the target code — understand its current structure and public API
- 2. Find ALL callers and dependents using Grep:
- - Direct function/method calls
- - Import statements referencing the target
- - Type references (if applicable)
- - Configuration or dependency injection references
- 3. Map the dependency graph:
- - What does the target depend on?
- - What depends on the target?
- - Are there circular dependencies?
- 4. Identify the public API surface:
- - Which functions/methods/classes are called externally?
- - Which are internal-only (safe to change freely)?
- 5. Note any dynamic references (string-based lookups, reflection, decorators)
-
- Return:
- - Complete caller list with file:line references
- - Dependency graph (what depends on what)
- - Public vs internal API surface
- - Risks: dynamic references, external consumers, serialization"
- subagent_type: "Explore"
- model: "haiku"
-
- Agent 2 - Test Coverage Analysis (Explore, Haiku):
- prompt: "Analyze test coverage for the refactoring target:
-
- Refactoring target: [DESCRIBE TARGET CODE]
-
- 1. Find ALL test files that test the target code:
- - Unit tests directly testing target functions/classes
- - Integration tests exercising the target indirectly
- - E2E tests that flow through the target
- 2. For each test, note:
- - What specific behavior it verifies
- - Which code paths it exercises
- - Which inputs and edge cases it covers
- 3. Identify GAPS in test coverage:
- - Functions/methods with no tests
- - Code branches not exercised (error paths, edge cases)
- - Public API methods without direct test coverage
- 4. Check for test patterns:
- - Test fixtures and helpers available
- - Mocking patterns used in the project
- - Test naming conventions
-
- Return:
- - List of test files with what they cover
- - Coverage gaps requiring characterization tests
- - Test patterns and fixtures available for reuse
- - Risk areas: untested code paths that refactoring could break"
- subagent_type: "Explore"
- model: "haiku"
- ```
-
- **Step 1.3: Synthesize Analysis**
-
- After both agents complete, synthesize findings:
- 1. Identify which parts of the target are safe to refactor (well-tested, internal-only)
- 2. Identify which parts are risky (untested, public API, dynamic references)
- 3. Determine if characterization tests are needed (Phase 2)
- 4. Plan the order of incremental changes
-
- **Step 1.4: Get Approval for Large Refactorings**
-
- If the refactoring involves: changes to >5 files, modifications to public APIs, moving code between modules, or changes affecting external consumers, use `AskUserQuestion` to present the scope analysis and get approval before proceeding.
-
- **Step 1.5: Complete Phase 1**
+ Map every caller and dependent of the target (Grep for calls, imports, type references, and dynamic/string-based lookups), and map its existing test coverage — what's tested, what's a gap. For a single-file target with an obvious blast radius, do this yourself; for a wider one, two Explore agents in parallel (callers/dependencies, then test coverage) save tokens — prompts in `references/task-chain.md`.
- ```
- TaskUpdate: { taskId: "2", status: "completed" }
- TaskList # Check that Task 3 is now unblocked
- ```
+ If the refactoring touches more than 5 files, changes a public API, or affects external consumers, use `AskUserQuestion` to confirm scope before proceeding.
### Phase 2: Characterization Tests
- **Goal**: Ensure sufficient test coverage exists to detect any behavioral change from the refactoring.
-
- **Step 2.1: Start Phase 2**
-
- ```
- TaskUpdate: { taskId: "3", status: "in_progress" }
- ```
-
- **Step 2.2: Assess Coverage Needs**
-
- Based on Phase 1 coverage analysis, determine which characterization tests are needed:
-
- - **Well-tested code** (>80% path coverage): Skip to Phase 3
- - **Partially tested** (some gaps): Add targeted characterization tests for untested paths
- - **Poorly tested** (major gaps): Add comprehensive characterization tests before proceeding
-
- **Step 2.3: Write Characterization Tests**
-
- For each coverage gap identified:
-
- 1. **Read the target code** to understand current behavior (including edge cases)
- 2. **Write tests that capture current behavior exactly**:
- - Test the function/method with representative inputs
- - Test edge cases (null, empty, boundary values)
- - Test error paths (invalid inputs, failure modes)
- - Test return values AND side effects
- 3. **Run the characterization tests** — they must ALL pass against the current (pre-refactoring) code
- 4. **Name tests clearly**: Use prefix `test_char_` or equivalent to distinguish characterization tests from behavioral tests
-
- ```
- Example characterization test (Python):
- def test_char_calculate_total_with_discount():
- """Characterization: captures current discount calculation behavior."""
- result = calculate_total(items=[100, 200], discount=0.1)
- assert result == 270.0 # Current behavior: discount applied to sum
-
- def test_char_calculate_total_empty_items():
- """Characterization: captures current behavior with empty input."""
- result = calculate_total(items=[], discount=0.1)
- assert result == 0.0
- ```
-
- **IMPORTANT**: Characterization tests document CURRENT behavior, not desired behavior. If the current code has a quirk, the test captures that quirk. The refactoring must preserve it.
-
- **Step 2.4: Verify Characterization Tests**
-
- Run the full test suite (including new characterization tests). All must pass.
-
- ```bash
- [DISCOVERED_TEST_COMMAND]
- ```
-
- **Step 2.5: Complete Phase 2**
+ Where Phase 1 found coverage gaps, write tests that capture CURRENT behavior — including quirks and edge cases, not desired behavior — before changing anything. Name them so they're identifiable as characterization tests (`test_char_*` in Python, `TestChar_*` in Go, a `characterization:` describe block in JS). Run the full suite; every one must pass against the pre-refactoring code. Skip this phase entirely when the target already has thorough coverage.
- ```
- TaskUpdate: { taskId: "3", status: "completed" }
- TaskList # Check that Task 4 is now unblocked
+ ```python
+ def test_char_calculate_total_with_discount():
+ """Characterization: captures current discount calculation behavior."""
+ result = calculate_total(items=[100, 200], discount=0.1)
+ assert result == 270.0 # current behavior: discount applied to sum
```
### Phase 3: Incremental Refactoring
- **Goal**: Apply the refactoring in small, verified steps. Each step must pass all tests.
-
- **Step 3.1: Start Phase 3**
-
- ```
- TaskUpdate: { taskId: "4", status: "in_progress" }
- ```
-
- **Step 3.2: Plan Incremental Steps**
-
- Break the refactoring into the smallest possible independent steps. Each step should be:
- - **Self-contained**: Makes sense on its own
- - **Verifiable**: Tests can confirm behavior is preserved
- - **Reversible**: Easy to revert if something breaks
-
- Common refactoring step sequences (see `references/patterns.md` for details):
-
- | Refactoring Type | Step Sequence |
- |---|---|
- | Extract method | 1. Create new method with copied code → 2. Test → 3. Replace original with call → 4. Test |
- | Extract class | 1. Create class with methods → 2. Test → 3. Delegate from original → 4. Test → 5. Update callers → 6. Test |
- | Rename | 1. Add new name alongside old → 2. Test → 3. Update callers → 4. Test → 5. Remove old name → 6. Test |
- | Move function | 1. Copy to destination → 2. Test → 3. Re-export from source → 4. Update callers → 5. Test → 6. Remove source → 7. Test |
- | Simplify conditional | 1. Extract condition to named variable/method → 2. Test → 3. Simplify logic → 4. Test |
- | Remove duplication | 1. Identify shared pattern → 2. Extract shared code → 3. Test → 4. Replace first usage → 5. Test → 6. Replace next usage → 7. Test |
-
- **Step 3.3: Execute Each Step**
-
- For EACH incremental step:
-
- 1. **Make the change** — one small structural change using Edit tool
- 2. **Run tests immediately** — using discovered test command
- ```bash
- [DISCOVERED_TEST_COMMAND]
- ```
- 3. **If tests pass** — proceed to next step
- 4. **If tests fail** — STOP. Analyze the failure:
- - Is it a behavioral change? → Revert and find a smaller step
- - Is it a test that needs updating? → Only if the test was testing implementation details (not behavior)
- - Is it a pre-existing failure? → Compare with baseline from Phase 0
-
- **CRITICAL**: Never skip the test run between steps. Never batch multiple steps before testing. The discipline of test-after-every-change is what makes refactoring safe.
-
- **Step 3.4: Handle Complex Refactorings**
-
- For refactorings spanning multiple files:
-
- 1. **Update the target first** — make the structural change in the primary file
- 2. **Update callers one at a time** — change each caller individually, testing after each
- 3. **Clean up** — remove old code, update imports, testing after each removal
-
- For refactorings requiring temporary duplication:
-
- 1. **Create the new structure** alongside the old
- 2. **Test** — both old and new should work
- 3. **Migrate callers** one at a time to the new structure, testing after each
- 4. **Remove the old structure** once all callers are migrated
- 5. **Final test** — full suite
+ Break the change into the smallest independently-verifiable steps. See [references/patterns.md](references/patterns.md) for the step sequence per technique (extract method, extract class, rename, move, simplify conditional, remove duplication, inline, decompose large function). For each step: make the change, run tests immediately.
- **Step 3.5: Complete Phase 3**
+ Tests fail → stop, don't push through. Revert if it's a behavioral change and find a smaller step; only touch the test itself if it was asserting an implementation detail, not behavior; and check whether it's actually a pre-existing baseline failure. Never batch multiple steps before testing — that discipline is what separates refactoring from a rewrite in disguise.
- ```
- TaskUpdate: { taskId: "4", status: "completed" }
- TaskList # Check that Task 5 is now unblocked
- ```
+ For multi-file changes: update the target first, then update callers one at a time (testing after each), then clean up dead code last. When the change needs temporary duplication, keep old and new structures working side by side until every caller has migrated, then remove the old one.
### Phase 4: Final Verification
- **Step 4.1: Start Phase 4**
-
- ```
- TaskUpdate: { taskId: "5", status: "in_progress" }
- ```
-
- **Step 4.2: Run All Quality Checks**
-
- Run all quality checks using discovered commands from Phase 0.
+ Run every quality check the project has, against the Phase 0 baseline.
- **Quality Gates Checklist**:
+ **Quality Gates Checklist:**
- [ ] Full test suite passes (matches or exceeds Phase 0 baseline)
- - [ ] Characterization tests pass (behavior preserved)
- - [ ] No new linting errors introduced
- - [ ] No new type errors (if typed language)
- - [ ] Code is cleaner/simpler than before (the purpose of refactoring)
- - [ ] No accidental behavior changes
- - [ ] No debug code, commented-out code, or TODO comments left behind
- - [ ] All callers updated (no dangling references)
+ - [ ] Characterization tests pass
+ - [ ] No new lint or type errors
+ - [ ] Code is cleaner/simpler than before — the actual point of doing this
+ - [ ] No accidental behavior changes, debug code, or commented-out code
+ - [ ] All callers updated — no dangling references
- **If any check fails**: Fix the issue before proceeding. Do not commit broken code. Keep task as `in_progress` until all gates pass.
+ Then read the actual diff (`git diff`) end to end for anything not on that list: leftover debug statements, unrelated formatting churn, missed import updates, orphaned code. Fix before proceeding — don't leave the task `in_progress` with a known-broken gate.
- **Step 4.3: Review the Diff**
+ ### Phase 5: Final Commit
- Read the complete diff to verify only intentional changes exist:
+ Use the `git-commit` skill if available. Otherwise commit manually with type `refactor:`, a subject describing WHAT was restructured, a body explaining WHY, and always end with "No behavioral changes.":
- ```bash
- git diff
```
-
- Look for:
- - Unintended behavioral changes
- - Leftover debug statements
- - Unnecessary whitespace or formatting changes
- - Missing import updates
- - Orphaned code that should have been removed
+ refactor: extract validation logic from OrderProcessor
- **Step 4.4: Complete Phase 4**
+ Moved order validation into dedicated OrderValidator class to improve
+ separation of concerns. OrderProcessor now delegates to OrderValidator
+ for all input validation.
- ```
- TaskUpdate: { taskId: "5", status: "completed" }
- TaskList # Check that Task 6 is now unblocked
+ No behavioral changes.
```
- ### Phase 5: Final Commit
-
- **Step 5.1: Start Phase 5**
-
```
- TaskUpdate: { taskId: "6", status: "in_progress" }
- ```
-
- **Step 5.2: Create Commit**
-
- If `/cc-arsenal:git:commit` skill is available, use it. Otherwise, create a conventional commit manually:
-
- ```bash
- git add [files modified]
- git commit -m "refactor: [concise description of structural change]
+ refactor(auth): simplify token refresh conditional logic
- - [What was restructured and why]
- - [Key technique used: extract method, rename, simplify, etc.]
- - [Impact: files changed, callers updated]
+ Replaced nested if/else chain with guard clauses and extracted
+ isTokenExpired() helper.
- No behavioral changes."
+ No behavioral changes.
```
- **Commit message guidelines for refactoring:**
- - Type: `refactor:` (always — this is a structural change, not a fix or feature)
- - Subject: Describe WHAT was restructured
- - Body: Explain WHY this improves the codebase
- - Footer: Always include "No behavioral changes." to signal safety
+ ### Phase 6: Summary Report
- **Step 5.3: Complete Phase 5 and Refactoring**
+ Report what was restructured, which technique was used, files touched, before/after test results (must match), any characterization tests added, and the commit hash. Only state metrics (line counts, complexity, coverage %) that came from a command actually run this session — never estimate them.
- ```
- TaskUpdate: { taskId: "6", status: "completed" }
- TaskList # Show final status - all tasks should be completed
- ```
+ If Phase 0's scope gate deferred any behavior-changing work, state that by name here, explicitly, and point to `implement-feature`/`fix-bug` — even if it was already mentioned earlier in the run. The final message is what gets checked, not the earlier reasoning.
- ### Phase 6: Summary Report
+ ## Important Notes
- Report to the user with:
- - **Refactoring performed**: What structural changes were made
- - **Technique used**: Extract method, rename, simplify, move, etc.
- - **Files modified**: List with brief description of changes
- - **Behavior verification**: Test results before and after (matching)
- - **Characterization tests added**: List of new tests if any
- - **Code quality improvements**: Metrics if available (reduced duplication, fewer lines, better naming)
- - **Commit info**: Commit hash and message
+ - **Tests before and after every change** — non-negotiable.
+ - **No behavior changes** — refactoring changes structure only; if tests break, revert.
+ - **Minimal scope** — refactor only what was requested; resist "while I'm here" changes to adjacent code.
+ - **Ask when unsure** — better to clarify scope than to over-refactor.
## Additional Resources
- For detailed refactoring patterns, step sequences, and safety practices, see:
- - [references/patterns.md](references/patterns.md) - Refactoring catalog with step-by-step procedures
-
- ## Important Notes
-
- - **Always run Phase 0 first**: Never assume which tools are available
- - **Tests before and after every change**: This is non-negotiable
- - **Characterization tests for untested code**: Never refactor code without test coverage
- - **One step at a time**: Never combine multiple refactoring operations
- - **No behavior changes**: Refactoring changes structure only — if tests break, revert
- - **Ask when unsure**: Better to clarify scope than to over-refactor
- - **Minimal scope**: Refactor only what was requested — resist the urge to "improve" adjacent code
- - **Document the change**: Clear commit message explaining what and why
+ - [references/patterns.md](references/patterns.md) — refactoring catalog with step-by-step procedures per technique; load when picking the step sequence for a specific refactoring type.
+ - [references/task-chain.md](references/task-chain.md) — `TaskCreate`/`TaskUpdate` templates and Explore-agent prompts; load when running the full multi-file task chain (Phase 0-1).