Refactor Code
Process
- Confirm the constraint (ask if not provided):
- Invariant: what must NOT change (behavior, API, tests passing)
- Dimension (pick ONE):
- Readability (clearer naming, simpler control flow)
- Modularity (break apart, extract, separate concerns)
- Performance (reduce allocations, optimize hot paths)
- Type safety (tighten types, eliminate
any, add guards) - Deduplication (consolidate repeated patterns)
- Context: why this refactor, what pain it solves
Always pick ONE dimension. Multi-axis refactors produce unreadable diffs and are impossible to review.
- Load context:
- Read relevant standards from
.agents/standards/ - Read relevant common-mistakes from
.agents/common-mistakes/
- Outline the plan:
- Specific transformations to apply
- Order (each step leaves the check command passing)
- What the code will look like after (brief description, not full code)
- Risks or tricky parts
- Execute incrementally: One step at a time. Confirm tests pass between steps. If something breaks, roll back one step, not the whole refactor.
- Verify the invariant:
- Run the project's check command
- Diff the public API/interface — confirm nothing changed externally
- List any behavioral differences (there should be zero)
Rules
- ALWAYS constrain to ONE dimension. Multi-axis refactors produce unreadable diffs.
- Think in systems. When special cases or duplicates are members of a real class, refactor toward the one structure that serves the whole class, not a local tidy-up of each instance.
- Each step must leave tests passing
- A refactor diff should be "boring" — moves, renames, restructures. No logic changes.
- If you discover a bug during refactoring, note it for a separate fix PR. Never mix refactoring and bug fixes.
- Check
.agents/common-mistakes/for relevant patterns before and after - Big-output discipline. Heavy command output (project check, full
git diff, repo-wide search, long log, large fetch) goes to/tmp/hawk-<skill>-<step>.log, thenrg -n '<pattern>' /tmp/hawk-<skill>-<step>.log | head -50extracts what you need. Read only the required lines from the file. See README → Big-output discipline.