Raw view: Refactor safely

No invisible, zero-width, or bidi-control characters detected.

---
description: Refactor a file, function, or module in small verified steps without changing behavior
argument-hint: <path or symbol> [goal, e.g. "extract the validation into its own module"]
allowed-tools: Read, Grep, Glob, Edit, Write, Bash
disable-model-invocation: true
---

Refactor `$0`. Goal: $1

Working tree (must be clean before starting):
!`git status --porcelain`

Rules for this task:
- Behavior does not change. Same inputs, same outputs, same errors, same side effects. If you discover a bug, note it and leave it; fixing it is a separate commit.
- Public names, signatures, and exports stay the same unless the goal explicitly includes renaming; when it does, update every call site found with Grep in the same step.
- Each step is small enough to describe in one sentence and leaves the suite green.

Procedure:
1. If the tree is dirty, stop and ask for a commit or stash.
2. Find the tests that cover the target: Grep the test directories for its exported names. Run them and record the pass count as the baseline. If coverage is thin, write characterization tests first (tests that assert current behavior, including odd behavior) and commit them as `test: characterize <target> before refactor`.
3. Write the plan as a numbered list of steps, each a single transformation: extract function, inline variable, move file, replace conditional with lookup, introduce parameter object, split module. Show the plan and continue without waiting unless the plan touches more than 10 files.
4. For each step: make the change, run the covering tests (full suite every third step or whenever imports change), and show the summary line. Green: continue. Red: revert that step with `git checkout -- <files>` (or `git restore`) and either try a smaller transformation or report why the step is not safe.
5. Commit after each green step or logical group as `refactor(<scope>): <step>`.
6. Finish with the full suite, typecheck, and lint. Report.

Output:
## Refactor: `$0`
Goal: ...
Baseline: <N tests passing>
| Step | Files | Suite | Commit |
Final: <N passing> | typecheck ok | lint ok
Bugs noticed, not fixed: ...
Behavior that could not be preserved exactly (and why): ...