---
type: skill
domain: development
links: [Corpus_Callosum/CONSTITUTION.md, PULSE_OS.md]
---

# REFACTOR_DRUID.md
> **ROLE:** CODE EVOLUTIONIST
> **TRIGGER:** "REFACTOR" / "CLEAN UP" / "SIMPLIFY"

## Step-by-Step Protocol
1. **Detect code smells** — run `brain_query.py --query "refactoring anti-patterns"`. Check for: Long Method (>30 lines), Large Class (>200 lines), Feature Envy (method uses another class's data more than its own), Duplicated Code (>3 lines repeated 2+ times), Shotgun Surgery (one change requires editing 3+ files).
2. **Verify test coverage** — before touching anything, confirm tests exist for the code being refactored. If coverage <80%, write tests FIRST. Run `pytest --cov=<module> --cov-report=term-missing` to see exact uncovered lines.
3. **Apply Fowler patterns** — choose the right refactoring: Extract Method (long functions), Extract Class (god objects), Replace Conditional with Polymorphism (switch/if chains), Introduce Parameter Object (3+ related params), Move Method (feature envy). One pattern per commit.
4. **Execute in micro-steps** — each step must pass all tests. Sequence: rename -> extract -> inline -> move. Never combine two refactorings in one commit. Run tests after EVERY change. If tests break, revert immediately.
5. **Validate and record** — compare before/after: line count, cyclomatic complexity, test pass rate. Save results with `pulse_save.py`. Post remaining work to task board if scope expanded.

## Metrics & Thresholds
- **Max function length:** 30 lines (extract if exceeded)
- **Max file length:** 200 lines (split if exceeded; PULSE convention from ASOP)
- **Max parameters:** 3 per function (use Parameter Object or config dict for more)
- **Cyclomatic complexity:** <=10 per function (measure with `radon cc -s <file>`)
- **Duplication:** 0 blocks of >3 identical lines (use `radon raw` or `jscpd` to detect)
- **Test coverage:** >=80% on refactored code before AND after

## Good Example
```python
# BEFORE: Long Method smell (42 lines, 3 concerns mixed)
def process_task(task):
    # validate... 15 lines
    # transform... 15 lines
    # save... 12 lines

# AFTER: Extract Method (Fowler) — each concern isolated
def process_task(task: dict) -> Result:
    validated = _validate_task(task)        # 15 lines, testable alone
    transformed = _transform_task(validated) # 15 lines, testable alone
    return _save_task(transformed)           # 12 lines, testable alone

def _validate_task(task: dict) -> ValidTask:
    """Raises ValueError if task fails quality gates."""
    if len(task.get("title", "")) < 5:
        raise ValueError("Title must be >= 5 chars")
    if task.get("domain") not in VALID_DOMAINS:
        raise ValueError(f"Unknown domain: {task['domain']}")
    return ValidTask(**task)
```

## Anti-Patterns
1. **Big-bang refactoring** — rewriting an entire module in one commit; if tests fail you can't tell what broke. One pattern, one commit.
2. **Refactoring without tests** — you're flying blind; write characterization tests first (`assert current_output == expected` for existing behavior).
3. **Premature abstraction** — extracting a base class after seeing duplication once; wait for 3 occurrences (Rule of Three) before abstracting.

## Tools to Use
- `python pulse/brain/brain_query.py --query "refactoring <module>"` — check prior refactoring attempts and lessons
- `python pulse/tasks/pulse_relay.py --tasks "Refactor <module>:development:standard"` — delegate sub-refactorings
- `python pulse/brain/pulse_save.py --agent refactor_druid --learnings "what you learned"` — record patterns found

## Verification Checklist
- [ ] Tests pass before AND after every micro-step (zero regressions)
- [ ] No function exceeds 30 lines or cyclomatic complexity 10
- [ ] No file exceeds 200 lines (or has a documented exception)
- [ ] Each commit contains exactly one refactoring pattern
- [ ] Duplication check: zero repeated blocks >3 lines across refactored code
