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.

You get: Working code with an explanation

More like this

The prompt

claude-code-behavior-preserving-refactor-with-characterization-tests-and-staged-commits.md
Role: You are Claude Code acting as a staff engineer performing a behavior-preserving refactor in {repo_path}. You value reversibility, small steps, and evidence over speed.

Context: The goal is {refactor_goal} for the target {target_module}. The decision this supports is whether the refactor can be merged as a series of low-risk commits and whether the team should proceed with a larger follow-up. Read CLAUDE.md and project docs first to learn conventions, linters, and test commands.

Task: Map the target, pin its behavior with tests, refactor incrementally, and prove behavior is unchanged.

Inputs (request anything missing; list assumptions separately):
- Target module or files: {target_module}
- Refactor goal and pain points: {refactor_goal}
- Public interfaces that must not change: {stable_interfaces}
- Test, lint, and type-check commands: {verify_commands}
- Current test coverage notes (optional): {coverage_notes}
- Time or size budget (max files or lines changed): {change_budget}
- Commit style: {commit_style}

Constraints:
- No behavior changes. If you find a bug, record it under Findings and do not fix it in this refactor.
- Do not alter {stable_interfaces} signatures or exported names.
- One logical change per commit. Run {verify_commands} after each step and stop if anything regresses.
- Do not commit or push unless the user explicitly says so; otherwise prepare commit messages only.
- Do not add dependencies. Stay within {change_budget} or ask first.
- Report only results you observed. Mark skipped checks as not run.

Workflow:
1. Inventory: use Glob, Grep, and Read to list the target files, callers, and tests. Build a dependency map of who imports what.
2. Baseline: run {verify_commands} and record the pass/fail state before any edit. Note pre-existing failures.
3. Characterization: for under-tested paths, write tests that capture current behavior, including odd outputs. Confirm they pass on unmodified code.
4. Plan: present an ordered refactor plan as a checklist with each step's risk (low/medium/high) and rollback method. Wait for approval if any step is high risk.
5. Execute: apply steps one at a time, using small edits. After each step run the fast tests, then the full {verify_commands} at milestones.
6. Compare: review git diff for accidental changes, renamed exports, and changed error messages.
7. Summarize findings, remaining debt, and follow-ups.

Output format:## Assumptions and Missing Information
## Target Map (table: file | responsibility | callers | test coverage)## Baseline Results
## Refactor Plan (table: step | change | risk | rollback)
## Characterization Tests Added (file | behavior pinned)
## Execution Log (step | verification command | result | run: yes/no)
## Final Diff Summary (files changed, lines added/removed)
## Findings Not Fixed (bugs, smells, with file:line)
## Risk Register
## Proposed Commit Messages
## Next Actions

Acceptance criteria:
- Baseline and final verification results match, with no newly failing tests.
- Stable interfaces are unchanged, confirmed by diff or type check.
- Every step is independently reviewable and reversible.
- Characterization tests exist for each behavior the refactor could plausibly alter.
- The change stays within {change_budget} or the overage is justified.

Quality checks before finishing:
- Did any step mix refactoring with behavior change?
- Did I check dynamic usage such as reflection, string-based imports, or config references that Grep might miss?
- Are there callers outside the repo, such as published packages or docs?
- Is every claim labeled observed or inferred?

Example output

AI-written example
# ===== refactor-report: invoice-service / src/billing/totals.py =====
# Assumptions: Python 3.11; CLAUDE.md says "ruff + mypy --strict on src"; no commits made (messages only).
# Baseline (observed): pytest -q -> 412 passed, 2 skipped | ruff check -> clean | mypy src -> clean
# Final (observed):    pytest -q -> 419 passed, 2 skipped | ruff check -> clean | mypy src -> clean
# Budget: max 4 files / 150 lines. Actual: 3 files, +96 / -41.
# Stable interfaces (unchanged, confirmed by diff + mypy): calculate_invoice_total(invoice, *, tax_table=None), InvoiceTotals
# Dynamic usage check: grep for "totals" in YAML/config and string imports -> none found (observed).
#   External callers (published package, docs) -> not checked (not run).
#
# Findings NOT fixed:
#   totals.py:58  round() uses banker's rounding; 0.125 -> 0.12 (pinned by test)
#   totals.py:73  lines with qty <= 0 are silently skipped, no warning
#
# Risk register:
#   R1 low    helper extraction changes evaluation order -> pinned by discount-then-tax tests
#   R2 medium float rounding drift if tax is computed per line vs per invoice -> kept per invoice
#   R3 low    external callers importing private names -> helpers are underscore-prefixed, new only
# Rollback: each commit is independent; `git revert <sha>` in reverse order. Commit 1 (tests) is safe to keep.

# ----- commit 1 -----
test(billing): pin current behavior of calculate_invoice_total

diff --git a/tests/billing/test_totals_characterization.py b/tests/billing/test_totals_characterization.py
new file mode 100644
--- /dev/null
+++ b/tests/billing/test_totals_characterization.py
@@ -0,0 +1,38 @@
+import pytest
+from billing.totals import calculate_invoice_total
+from tests.billing.factories import make_invoice, line
+
+
+def test
Generated from this prompt by AI. Your results will vary.

Tips and common edits

Use in a clean git working tree so the diff is easy to review and revert. Supply the exact test and lint commands to avoid guessing. If the plan includes high-risk steps, approve them individually. Best for modules with identifiable callers; for monorepos, name the package.

Questions about this prompt

More in Claude Code

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.

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.

Claude Code Root-Cause Bug Investigation with Failing Test and Minimal Patch

Directs Claude Code to reproduce a bug, trace it to a root cause using repository evidence, write a failing regression test, and apply the smallest safe fix. Ends with a verified diff, risks, and next actions.

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 Hook Writer: Auto-Run Lint, Typecheck or Tests After Edits

Produces a PostToolUse hook entry for settings.json, the script it calls and a concrete procedure to test that the check runs after file edits.

Claude Code Plan-Then-Implement a Feature With Approval Checkpoints

Makes Claude Code explore the repo, write a step-by-step plan for your approval, then build the feature in small verified steps, stopping at each checkpoint for your go-ahead.

Codebase Tour for a Specific Task

Explores a repo through the lens of your task and explains the architecture, key files and data flow, then says where to start.

Coding Agent Task Brief with Guardrails, Test Plan, and Rollback Steps

Creates a scoped brief for an AI coding agent that limits file changes, defines tests, and includes a rollback plan and review checklist.