Characterization-Test-Backed Refactor with Incremental Commits

Guides Claude Code to refactor a module safely by first pinning current behavior with characterization tests, then making small, reversible commits. Helps you decide whether the refactor preserved behavior and is worth merging.

You get: Job-to-be-done and merge decision supported, baseline and characterization tests added

More like this

The prompt

characterization-test-backed-refactor-with-incremental-commits.md
Role: You are a refactoring specialist operating in Claude Code with edit, test, and local git commit permissions in {repo_path}.

Context: The module {target_module} has a problem: {refactor_motivation}. I must decide whether the refactor improves maintainability without changing behavior, and whether to merge it as is.

Task: Refactor {target_module} toward {target_design} using small, individually verifiable commits, protected by characterization tests.

Inputs:
- Target module or files: {target_module}
- Motivation and pain points: {refactor_motivation}
- Desired design or outcome: {target_design}
- Test command and lint command: {test_command}
- Public API that must not change: {public_api}
- Out-of-scope areas: {out_of_scope}

Constraints:
- Behavior must remain unchanged unless explicitly listed under Intentional changes. Default is none.
- Do not change the public API in {public_api}, including signatures, exports, and error types.
- Each commit must leave the tests green. Use messages in the form refactor(scope): what and why.
- No new dependencies. Do not touch files in {out_of_scope}.
- Do not claim tests passed without running them and reading the output. Report pre-existing failures separately.
- State assumptions separately from verified facts.

Workflow:
1. Map the module: callers, dependencies, side effects, and existing test coverage. Record the baseline test and lint results.
2. Identify coverage gaps on behavior you will touch. Write characterization tests that assert current actual behavior, even if it looks odd, and flag suspected bugs without fixing them.
3. Propose an ordered refactor sequence of 3 to 8 steps, each small enough to review in under 10 minutes.
4. Execute one step at a time: edit, run tests and lint, commit. Stop and report if a step breaks tests in a way you cannot explain.
5. Compare final structure to the target design and note gaps.

Output format:
1. Job-to-be-done and merge decision supported
2. Baseline (test and lint results before changes)
3. Characterization tests added (table: test | behavior pinned | file)
4. Commit log (table: hash | message | files changed | tests result)
5. Before and after structure summary (bulleted, with metrics such as file length or function count if measured)
6. Suspected bugs found but intentionally not fixed
7. Assumptions, risks, and missing information
8. Next actions

Acceptance criteria:
- Test results after every commit are reported, and all are green or explained.
- Public API is unchanged, shown by tests or diff evidence.
- Characterization tests were committed before the refactor steps that depend on them.
- Final diff is reviewable commit by commit.

Quality checks:
- Run git log --oneline and confirm each commit has one purpose.
- Search for remaining usages of removed or renamed internals.
- Confirm no behavior changes are hidden in the commits by reviewing the diff for logic edits.
- Verify that metrics you cite were actually measured.

Tips and common edits

Best on modules with moderate test coverage and clear boundaries. Use a dedicated branch. For large modules, run the prompt per sub-module, and have Claude Code use subagents only for read-only exploration.

Questions about this prompt

Claude Code Behavior-Preserving Refactor with Characterization Tests and Staged Commits

Guides Claude Code to refactor a module safely by first pinning current behavior with characterization tests, then applying small reversible steps with verification after each. Delivers a diff, risk register, and rollback plan.

Agent Session Handoff Brief with Resume Checklist and Verified State

Makes Claude Code produce a handoff file capturing goal, verified repo state, decisions, blockers, and exact resume commands so another engineer or agent session can continue without rework. Use it before ending a long task.

Claude Code Repo Recon and Implementation Plan for a New Feature

Has Claude Code inspect a repository read-only and produce an evidence-based implementation plan with file-level changes, tests, risks, and open questions. Use it to decide whether to start, split, or clarify a feature before any code is written.

Pre-Merge Self-Review of a Git Diff: Correctness, Security, and Test Gaps

Has Claude Code review a branch diff like a skeptical maintainer, producing severity-ranked findings with evidence and a clear merge, fix, or block recommendation. Use it before opening or approving a pull request.

Reproduce-First Bug Fix: Failing Test, Minimal Patch, and Regression Proof

Directs Claude Code to reproduce a reported bug with a failing test, apply the smallest fix, and prove the fix with command output. Use it to decide whether a bug is fixed and safe to merge.

Characterization Tests Before a Refactor

Writes tests that lock in a module's current behavior, including edge cases and quirks, so you can refactor safely.

Cursor Characterization-Test-First Refactor of a Legacy Module

Has Cursor lock in current behavior with characterization tests before restructuring a legacy module in small steps, so you can decide whether the refactor preserved behavior and is safe to merge.

Cursor Refactor of a Component With Zero Behaviour Change

Has the Cursor agent restructure a messy component into smaller pieces while proving the behaviour stays identical, using existing tests or new characterization tests first.

Subagent Fan-Out Plan for a Large Codebase Migration

Plans a big migration so an orchestrating agent can split it into independent chunks for parallel subagents, each with a clear brief, a verification command and merge rules.

Agent Run Post-Mortem: Trace Root Cause and Prompt or Tool Fixes

Analyzes a pasted agent trace to find the first real failure and proposes exact prompt rewrites or tool changes, each with a test.

Checkpoint and Rollback Manager with Compensation Steps and Failure Injection Tests

Guides Claude Code to implement checkpoint snapshots, rollback modes, and compensating actions for side-effecting agent phases, then prove them with failure-injection tests. Helps you decide the rollback strategy per phase.

Claude Code Feature Implementation Plan and Build from a Ticket with Repo Convention Discovery

Has Claude Code investigate how similar features are built in the repository, produce an implementation plan with acceptance tests, then implement it in verified increments. Surfaces risks, open questions, and next actions before and after coding.