Code Refiner
A structured, multi-pass code refinement skill that transforms complex, verbose, or tangled code
into clean, idiomatic, maintainable implementations — without changing what the code does.
Philosophy
The goal is not fewer lines. The goal is code that a tired engineer at 2am can read, understand,
and safely modify. Every change must pass three tests:
- Behavioral equivalence — identical inputs produce identical outputs, side effects, and errors
- Cognitive load reduction — a reader unfamiliar with the code understands it faster after the change
- Maintenance leverage — the change makes future modifications easier, not harder
When clarity and brevity conflict, clarity wins. When idiom and explicitness conflict, consider the
team's experience level. When DRY and locality conflict, prefer locality for code read more than modified.
Prerequisites
- git — used in Phase 1 for scope detection (
git diff) when the user doesn't specify target files
- Python 3.10+ — required to run
scripts/complexity_report.py for quantitative complexity metrics
Workflow
Follow this sequence. Each phase builds on the previous one. Do not skip phases, but adapt depth
to the scope of the request (a single function gets a lighter pass than a full module).
Phase 1: Reconnaissance
Before touching anything, build a mental model:
- Identify scope — What files/functions are in play? If the user hasn't specified, check recent
git modifications:
git diff --name-only HEAD~5 or git diff --staged --name-only
- Detect language and ecosystem — Read file extensions, imports, config files (package.json,
pyproject.toml, go.mod, Cargo.toml). Load the appropriate language reference from
references/ if needed for idiom-specific guidance
- Read project conventions — Check for CLAUDE.md, .editorconfig, linter configs (eslint,
ruff, golangci-lint, clippy). These override generic idiom preferences
- Understand test coverage — Locate test files. If tests exist, note the test runner so you
can verify behavioral equivalence after changes
- Baseline complexity snapshot — For each target function/method, mentally note:
- Nesting depth (max indentation levels)
- Number of branches (if/else/match/switch arms)
- Number of early returns vs single-exit
- Parameter count
- Lines of code
- Number of responsibilities (does it do more than one thing?)
Phase 2: Structural Analysis
Identify what's actually wrong before reaching for solutions. Categorize issues by severity:
Critical (always fix):
- Dead code (unreachable branches, unused variables/imports)
- Redundant operations (double-checking the same condition, re-computing cached values)
- Logic that can be replaced by a stdlib/language built-in
- Mutation of shared state that could be avoided
High (fix unless there's a clear reason not to):
- Functions with >3 levels of nesting
- Functions with >5 parameters
- God functions (>40 lines or >3 responsibilities)
- Repeated code blocks (3+ occurrences of similar logic)
- Inverted or confusing boolean logic
- Stringly-typed enumerations
Medium (fix when it improves clarity without adding risk):
- Unclear variable/function names
- Missing or misleading type annotations
- Unnecessary intermediate variables
- Over-abstraction (wrappers that add no value)
- Comments that restate the code instead of explaining why
Low (fix only in a dedicated cleanup pass):
- Inconsistent formatting (defer to linter)
- Import ordering
- Trailing whitespace, line length
Phase 3: Refactoring Execution
Apply changes using these tactics, ordered by impact-to-risk ratio:
3a. Eliminate Dead Weight
Remove before restructuring. Less code = less to think about.
- Delete unused imports, variables, functions
- Remove unreachable branches (but verify they're truly unreachable)
- Strip comments that restate the obvious (keep comments that explain why)
- Remove no-op wrapper functions that just forward calls
3b. Flatten Structure
Reduce nesting and cognitive load:
- Guard clauses: Convert deep
if nesting to early returns
- Extract conditions: Name complex boolean expressions (
is_valid_order = ...)
- Decompose loops: If a loop does filter + transform + accumulate, break it apart
(or use language-appropriate constructs: list comprehensions, iterators, streams)
- Invert conditionals: When the
else branch is the "happy path", flip it
3c. Consolidate and Name
Make the code's intent visible:
- Extract functions for repeated logic or distinct responsibilities
- Name by what it accomplishes, not how it works
- Functions should do one thing at one level of abstraction
- Replace magic values with named constants
- Rename for intent:
data → user_records, process → validate_and_enqueue
- Group related parameters into a config/options struct when count > 3
3d. Leverage Language Idioms
Apply language-specific patterns (consult references/<language>.md for details):
- Python: comprehensions, context managers, dataclasses, structural pattern matching
- Go: table-driven tests, error wrapping, functional options, interface satisfaction
- TypeScript: discriminated unions, branded types, const assertions, satisfies
- Rust: iterator chains,
? operator, From/Into, newtype pattern
3e. Tighten Types
Types are documentation that the compiler checks:
- Add return type annotations to public functions
- Replace stringly-typed parameters with enums/unions
- Narrow
any/interface{} to specific types where possible
- Use branded/newtype patterns for identifiers that shouldn't be confused
Phase 4: Verification
Never skip this phase. Simplification that breaks behavior is not simplification.
- Run existing tests — If a test suite exists, run it. Report pass/fail.
- Run linter/type checker — If configured, run it. Fix new violations your changes introduced.
- Manual trace — For each refactored function, mentally trace one happy-path and one
error-path input through the old and new code. Confirm identical behavior.
- Side effect audit — If the original code had side effects (I/O, mutation, logging),
verify the new code preserves them in the same order and conditions.
If tests fail or behavior diverges: revert the specific change, don't try to fix the test.
Phase 5: Report
Present changes as a structured summary. This is important — the developer needs to understand
and trust what changed before committing.
For each file modified, provide:
## <filename>
### Changes
- [Critical] Removed unreachable error branch in `parse_config` (dead code after L42 guard)
- [High] Extracted `validate_credentials()` from 60-line `handle_login()` (was 3 responsibilities)
- [Medium] Renamed `d` → `document`, `proc` → `process_batch`
### Complexity Delta
- `handle_login`: 4 levels nesting → 2, 8 branches → 5
- `parse_config`: removed 12 lines of dead code
### Risk Assessment
- Low risk: all changes are structural, no logic modifications
- Tests: 47/47 passing
Adjust verbosity to scope. Single-function cleanup gets a one-liner. Multi-file refactor gets the full report.
Behavioral Constraints
These are hard rules. Do not violate them regardless of how much cleaner the code would look:
- Never change observable behavior — This includes error messages, log output, return values,
side effect ordering, and exception types
- Never remove error handling — Even if it looks redundant. Defensive code often exists
for a reason you can't see from the code alone
- Never introduce new dependencies — Simplification adds nothing to the dependency tree
- Never refactor code outside the specified scope — Unless the user explicitly asks for a
broader pass. Resist the urge to "fix one more thing"
- Preserve public API surfaces — Function signatures, export names, and type definitions
visible to consumers do not change without explicit user approval
- Respect existing tests — If a test asserts specific behavior, that behavior is a requirement,
even if it seems wrong. Flag it in the report, don't change it
Configuring Scope and Aggressiveness
The user may specify different modes. If they don't, default to standard.
| Mode |
Scope |
Severity Threshold |
Test Requirement |
quick |
Single file or function |
Critical + High only |
Tests recommended |
standard |
Recent git changes |
Critical + High + Medium |
Tests required if they exist |
deep |
Entire module/package |
All severities |
Tests mandatory |
surgical |
User-specified lines/functions |
All severities |
Manual trace sufficient |
The user can specify mode by saying things like "just do a quick pass" or "deep clean this module".
When NOT to Refine
Push back (politely) if:
- The code has no tests and the user wants a deep refactor → suggest writing tests first
- The code is auto-generated (protobuf, OpenAPI, ORM models) → suggest modifying the generator
- The request is really a feature change disguised as "cleanup" → clarify intent
- The code is in a hot path and "simplification" would introduce allocation/copies → flag the tradeoff
Language References
For language-specific idiom guidance, read the appropriate reference file:
references/python.md — Python-specific patterns, anti-patterns, and stdlib alternatives
references/go.md — Go idioms, error handling patterns, and interface design
references/typescript.md — TypeScript/JavaScript patterns, type narrowing, and module design
references/rust.md — Rust idioms, ownership patterns, and iterator usage
Only load the reference file for the language(s) in the current scope. These provide detailed
pattern catalogs that supplement the general methodology above.
Rationalizations
| Rationalization |
Reality |
| "It's readable enough" |
"Enough" is not a standard — if the next developer needs to re-read a function 3 times, it's not readable |
| "Refactoring risks regressions" |
Not refactoring risks accumulating debt — run the test suite before and after, that's what tests are for |
| "This is how the codebase has always done it" |
Consistency with a bad pattern is still bad — improve incrementally, don't preserve anti-patterns |
| "The performance might get worse" |
Benchmark before and after — most readability refactors have zero performance impact; premature optimization is the root of all evil |
| "It's not broken, don't fix it" |
Refining isn't fixing — it's making working code maintainable, testable, and understandable for the next person |
| "I'll refactor the whole module later" |
Incremental refinement works; big-bang rewrites fail — improve what you touch now |
Red Flags
- Changing behavior while claiming "just a refactor" — refining must preserve all existing behavior
- Touching code outside the declared scope without justification
- Removing error handling or validation during simplification
- Introducing new abstractions for one-time operations
- Refactoring without running the test suite before and after
- Making style changes to code that wasn't part of the original task
Verification
1---2name: code-refiner3description: Deep code simplification and refactoring preserving behavior across Python, Go, TypeScript, Rust. Targets complexity, anti-patterns, readability debt. Triggers on: "simplify this code", "refactor for clarity", "reduce complexity", "make this more readable", "tech debt cleanup", "too much nesting".4---56# Code Refiner78A structured, multi-pass code refinement skill that transforms complex, verbose, or tangled code9into clean, idiomatic, maintainable implementations — without changing what the code does.1011## Philosophy1213The goal is **not** fewer lines. The goal is code that a tired engineer at 2am can read, understand,14and safely modify. Every change must pass three tests:15161. **Behavioral equivalence** — identical inputs produce identical outputs, side effects, and errors172. **Cognitive load reduction** — a reader unfamiliar with the code understands it faster after the change183. **Maintenance leverage** — the change makes future modifications easier, not harder1920When clarity and brevity conflict, clarity wins. When idiom and explicitness conflict, consider the21team's experience level. When DRY and locality conflict, prefer locality for code read more than modified.2223## Prerequisites2425- **git** — used in Phase 1 for scope detection (`git diff`) when the user doesn't specify target files26- **Python 3.10+** — required to run `scripts/complexity_report.py` for quantitative complexity metrics2728## Workflow2930Follow this sequence. Each phase builds on the previous one. Do not skip phases, but adapt depth31to the scope of the request (a single function gets a lighter pass than a full module).3233### Phase 1: Reconnaissance3435Before touching anything, build a mental model:36371. **Identify scope** — What files/functions are in play? If the user hasn't specified, check recent38 git modifications: `git diff --name-only HEAD~5` or `git diff --staged --name-only`392. **Detect language and ecosystem** — Read file extensions, imports, config files (package.json,40 pyproject.toml, go.mod, Cargo.toml). Load the appropriate language reference from41 `references/` if needed for idiom-specific guidance423. **Read project conventions** — Check for CLAUDE.md, .editorconfig, linter configs (eslint,43 ruff, golangci-lint, clippy). These override generic idiom preferences444. **Understand test coverage** — Locate test files. If tests exist, note the test runner so you45 can verify behavioral equivalence after changes465. **Baseline complexity snapshot** — For each target function/method, mentally note:47 - Nesting depth (max indentation levels)48 - Number of branches (if/else/match/switch arms)49 - Number of early returns vs single-exit50 - Parameter count51 - Lines of code52 - Number of responsibilities (does it do more than one thing?)5354### Phase 2: Structural Analysis5556Identify what's actually wrong before reaching for solutions. Categorize issues by severity:5758**Critical** (always fix):5960- Dead code (unreachable branches, unused variables/imports)61- Redundant operations (double-checking the same condition, re-computing cached values)62- Logic that can be replaced by a stdlib/language built-in63- Mutation of shared state that could be avoided6465**High** (fix unless there's a clear reason not to):6667- Functions with >3 levels of nesting68- Functions with >5 parameters69- God functions (>40 lines or >3 responsibilities)70- Repeated code blocks (3+ occurrences of similar logic)71- Inverted or confusing boolean logic72- Stringly-typed enumerations7374**Medium** (fix when it improves clarity without adding risk):7576- Unclear variable/function names77- Missing or misleading type annotations78- Unnecessary intermediate variables79- Over-abstraction (wrappers that add no value)80- Comments that restate the code instead of explaining _why_8182**Low** (fix only in a dedicated cleanup pass):8384- Inconsistent formatting (defer to linter)85- Import ordering86- Trailing whitespace, line length8788### Phase 3: Refactoring Execution8990Apply changes using these tactics, ordered by impact-to-risk ratio:9192#### 3a. Eliminate Dead Weight9394Remove before restructuring. Less code = less to think about.9596- Delete unused imports, variables, functions97- Remove unreachable branches (but verify they're truly unreachable)98- Strip comments that restate the obvious (keep comments that explain _why_)99- Remove no-op wrapper functions that just forward calls100101#### 3b. Flatten Structure102103Reduce nesting and cognitive load:104105- **Guard clauses**: Convert deep `if` nesting to early returns106- **Extract conditions**: Name complex boolean expressions (`is_valid_order = ...`)107- **Decompose loops**: If a loop does filter + transform + accumulate, break it apart108 (or use language-appropriate constructs: list comprehensions, iterators, streams)109- **Invert conditionals**: When the `else` branch is the "happy path", flip it110111#### 3c. Consolidate and Name112113Make the code's intent visible:114115- **Extract functions** for repeated logic or distinct responsibilities116 - Name by _what it accomplishes_, not _how it works_117 - Functions should do one thing at one level of abstraction118- **Replace magic values** with named constants119- **Rename for intent**: `data` → `user_records`, `process` → `validate_and_enqueue`120- **Group related parameters** into a config/options struct when count > 3121122#### 3d. Leverage Language Idioms123124Apply language-specific patterns (consult `references/<language>.md` for details):125126- Python: comprehensions, context managers, dataclasses, structural pattern matching127- Go: table-driven tests, error wrapping, functional options, interface satisfaction128- TypeScript: discriminated unions, branded types, const assertions, satisfies129- Rust: iterator chains, `?` operator, From/Into, newtype pattern130131#### 3e. Tighten Types132133Types are documentation that the compiler checks:134135- Add return type annotations to public functions136- Replace stringly-typed parameters with enums/unions137- Narrow `any`/`interface{}` to specific types where possible138- Use branded/newtype patterns for identifiers that shouldn't be confused139140### Phase 4: Verification141142**Never skip this phase.** Simplification that breaks behavior is not simplification.1431441. **Run existing tests** — If a test suite exists, run it. Report pass/fail.1452. **Run linter/type checker** — If configured, run it. Fix new violations your changes introduced.1463. **Manual trace** — For each refactored function, mentally trace one happy-path and one147 error-path input through the old and new code. Confirm identical behavior.1484. **Side effect audit** — If the original code had side effects (I/O, mutation, logging),149 verify the new code preserves them in the same order and conditions.150151If tests fail or behavior diverges: revert the specific change, don't try to fix the test.152153### Phase 5: Report154155Present changes as a structured summary. This is important — the developer needs to understand156and trust what changed before committing.157158For each file modified, provide:159160```text161## <filename>162163### Changes164- [Critical] Removed unreachable error branch in `parse_config` (dead code after L42 guard)165- [High] Extracted `validate_credentials()` from 60-line `handle_login()` (was 3 responsibilities)166- [Medium] Renamed `d` → `document`, `proc` → `process_batch`167168### Complexity Delta169- `handle_login`: 4 levels nesting → 2, 8 branches → 5170- `parse_config`: removed 12 lines of dead code171172### Risk Assessment173- Low risk: all changes are structural, no logic modifications174- Tests: 47/47 passing175```176177Adjust verbosity to scope. Single-function cleanup gets a one-liner. Multi-file refactor gets the full report.178179## Behavioral Constraints180181These are hard rules. Do not violate them regardless of how much cleaner the code would look:1821831. **Never change observable behavior** — This includes error messages, log output, return values,184 side effect ordering, and exception types1852. **Never remove error handling** — Even if it looks redundant. Defensive code often exists186 for a reason you can't see from the code alone1873. **Never introduce new dependencies** — Simplification adds nothing to the dependency tree1884. **Never refactor code outside the specified scope** — Unless the user explicitly asks for a189 broader pass. Resist the urge to "fix one more thing"1905. **Preserve public API surfaces** — Function signatures, export names, and type definitions191 visible to consumers do not change without explicit user approval1926. **Respect existing tests** — If a test asserts specific behavior, that behavior is a requirement,193 even if it seems wrong. Flag it in the report, don't change it194195## Configuring Scope and Aggressiveness196197The user may specify different modes. If they don't, default to **standard**.198199| Mode | Scope | Severity Threshold | Test Requirement |200| ---------- | ------------------------------ | ------------------------ | ---------------------------- |201| `quick` | Single file or function | Critical + High only | Tests recommended |202| `standard` | Recent git changes | Critical + High + Medium | Tests required if they exist |203| `deep` | Entire module/package | All severities | Tests mandatory |204| `surgical` | User-specified lines/functions | All severities | Manual trace sufficient |205206The user can specify mode by saying things like "just do a quick pass" or "deep clean this module".207208## When NOT to Refine209210Push back (politely) if:211212- The code has no tests and the user wants a deep refactor → suggest writing tests first213- The code is auto-generated (protobuf, OpenAPI, ORM models) → suggest modifying the generator214- The request is really a feature change disguised as "cleanup" → clarify intent215- The code is in a hot path and "simplification" would introduce allocation/copies → flag the tradeoff216217## Language References218219For language-specific idiom guidance, read the appropriate reference file:220221- `references/python.md` — Python-specific patterns, anti-patterns, and stdlib alternatives222- `references/go.md` — Go idioms, error handling patterns, and interface design223- `references/typescript.md` — TypeScript/JavaScript patterns, type narrowing, and module design224- `references/rust.md` — Rust idioms, ownership patterns, and iterator usage225226Only load the reference file for the language(s) in the current scope. These provide detailed227pattern catalogs that supplement the general methodology above.228229## Rationalizations230231| Rationalization | Reality |232|---|---|233| "It's readable enough" | "Enough" is not a standard — if the next developer needs to re-read a function 3 times, it's not readable |234| "Refactoring risks regressions" | Not refactoring risks accumulating debt — run the test suite before and after, that's what tests are for |235| "This is how the codebase has always done it" | Consistency with a bad pattern is still bad — improve incrementally, don't preserve anti-patterns |236| "The performance might get worse" | Benchmark before and after — most readability refactors have zero performance impact; premature optimization is the root of all evil |237| "It's not broken, don't fix it" | Refining isn't fixing — it's making working code maintainable, testable, and understandable for the next person |238| "I'll refactor the whole module later" | Incremental refinement works; big-bang rewrites fail — improve what you touch now |239240## Red Flags241242- Changing behavior while claiming "just a refactor" — refining must preserve all existing behavior243- Touching code outside the declared scope without justification244- Removing error handling or validation during simplification245- Introducing new abstractions for one-time operations246- Refactoring without running the test suite before and after247- Making style changes to code that wasn't part of the original task248249## Verification250251- [ ] All existing tests pass before and after refinement252- [ ] No behavioral changes — output/side-effects identical for all inputs253- [ ] Changes stay within declared scope — no drive-by edits to unrelated code254- [ ] Cyclomatic complexity reduced or unchanged — never increased255- [ ] No new abstractions introduced for single-use cases256- [ ] Linter and type checker pass: `ruff check` + `mypy --strict` or `tsc --noEmit` + `eslint`