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.

You get: Module analysis table, test gap table and refactor steps table

More like this

The prompt

cursor-characterization-test-first-refactor-of-a-legacy-module.md
Role: You are a refactoring specialist working in Cursor Agent mode on the module {module_path} in {repo_name}.

Context: The module is hard to change safely. The decision to support is whether the refactor preserved behavior and is ready to merge. Use @Files for {module_path} and its tests, @Codebase to find all consumers, and the terminal for real test output. Do not claim behavior is preserved without passing tests.

Task: Add characterization tests that capture current behavior, then refactor toward {refactor_goal} in small, verified steps.

Inputs:
- Module path: {module_path}
- Refactor goal (for example split responsibilities, remove duplication, add types): {refactor_goal}
- Public API that must not change: {public_api}
- Test command: {test_command}
- Lint or type-check command: {lint_command}
- Constraints (no new dependencies, style rules, max diff size): {constraints}
If an input is missing, list it under Missing information and state assumptions separately.

Workflow:
1. Read the module and list its responsibilities, side effects, and external dependencies.
2. Use @Codebase to list consumers and the existing tests that cover the module.
3. Identify coverage gaps. Write characterization tests that assert current behavior, including known quirks, and mark suspected bugs with a comment instead of fixing them.
4. Run {test_command}. All new tests must pass against the unchanged code.
5. Plan 3-6 refactor steps, each independently committable and no larger than one concern.
6. Execute one step at a time. After each step run {test_command} and {lint_command}, and stop if anything fails.
7. Review the final diff against {public_api} to confirm no signature or behavior changes.

Constraints:
- Do not change behavior and structure in the same step.
- Do not edit consumers unless a step requires it, and list any such edits.
- Follow existing style and rules in .cursor/rules.
- Ask before deleting files or exports.

Output format:
1. Assumptions and Missing information
2. Module analysis table: Responsibility | Side effects | Dependencies
3. Test gap table: Behavior | Covered before | Test added
4. Refactor steps table: Step | Change | Verification result
5. Final diff summary: File | Change | Reason
6. Suspected bugs found but not fixed
7. Risks and next actions

Acceptance criteria:
- Characterization tests pass before and after the refactor without being weakened.
- Public API in {public_api} is unchanged.
- Each step passes tests and lint independently.
- Suspected bugs are listed, not silently fixed.

Quality checks:
- Do tests cover error paths, boundary values, and side effects?
- Is each step small enough to review in a few minutes?
- Are all consumers confirmed unaffected via search or tests?
- Is anything unverified clearly labeled?

Example output

AI-written example
// src/billing/__tests__/invoiceTotals.characterization.test.js
// Repo: acme-storefront | Module: src/billing/invoiceTotals.js
// Public API (must not change): calculateInvoiceTotal(order, options?) -> { subtotal, discount, tax, shipping, total }
// Run: npm test -- invoiceTotals.characterization
// These tests assert CURRENT behavior, including quirks. Do not "fix" them during the refactor.
// Suspected bugs are tagged SUSPECTED BUG and are listed, not fixed.

jest.mock('../../lib/logger', () => ({ info: jest.fn() }));

const logger = require('../../lib/logger');
const { calculateInvoiceTotal } = require('../invoiceTotals');

const item = (sku, price, qty) => ({ sku, price, qty });

describe('calculateInvoiceTotal (characterization)', () => {
  beforeEach(() => jest.clearAllMocks());

  describe('happy path', () => {
    it('sums line items, applies default 8% tax and flat shipping under 100
Generated from this prompt by AI. Your results will vary.

Tips and common edits

Best for modules with weak test coverage. Keep Cursor in Agent mode but accept one refactor step at a time, committing between steps. If tests need mocks for I/O, tell Cursor which fixtures already exist so it reuses them.

Questions about this prompt

More in Cursor

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 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.

Cursor Incremental Dependency Migration Plan and Codemod Execution

Plans and executes a library or framework version migration in Cursor in small, verifiable batches, with an impact inventory, rollback points, and per-batch test gates instead of one risky bulk edit.

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.

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.

Cursor Agent Bug Triage: Reproduce, Root-Cause, Fix, and Regression Test

Guides Cursor Agent through reproducing a bug, isolating the root cause with evidence, applying a minimal diff, and adding a regression test, ending with a verification checklist and risks.

Plan Before Edit: Cursor Plan-Mode Prompt for a Feature Request

Produces a read-only Cursor plan listing files in scope, ordered steps, specific risks and tests to run before any code is changed.

Unit Test Plan and Test Code for an Existing Function

Builds a behavior-based test matrix for a function or module and then generates test code in your framework. Covers edge cases, failures, and mocking boundaries, with coverage gaps stated honestly.

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.

Cursor Project Rules Generator for Your Repo's Stack

Has Cursor inspect your repository and write 3-5 scoped .mdc rules, each with globs, a description and a deliberately chosen attach mode.

Dependency Graph Planner for a Multi-Agent Software Release Workflow

Turns a list of release tasks into a dependency graph with parallel batches, critical path, shared-resource conflicts, and agent assignments. Supports the decision on what to run now versus wait on.

Edge-Case Test Suite for One Function in Your Existing Test Framework

Writes tests for a single function that cover normal inputs, boundaries, bad input and error paths, in the test framework your project already uses.