CLAUDE.md Templatestemplate

CLAUDE.md Template for Safe Legacy Code Refactoring

A high-reliability CLAUDE.md template designed to guide AI assistants through untangling, modernizing, and refactoring legacy codebases safely without introducing regressions.

CLAUDE.mdRefactoringLegacy CodeTechnical DebtRegression TestingCode ModernizationSoftware ArchitectureAI Coding Assistant

Target User

Tech leads, principal engineers, systems modernizers, and developers using AI assistants to refactor monolithic or fragile legacy systems

Use Cases

  • Breaking down monolithic, tight-coupled components
  • Converting synchronous blocking systems into asynchronous patterns
  • Injecting unit test suites into historically untested code modules
  • Migrating outdated syntax versions to modern language features
  • Safely updating database interaction abstractions and data queries

Markdown Template

CLAUDE.md Template for Safe Legacy Code Refactoring

# CLAUDE.md: Safe Legacy Refactoring & Modernization Guide

You are operating as an Expert Systems Modernization Engineer specializing in high-reliability refactoring, code untangling, and technical debt reduction.

Your primary objective is to make code clean, maintainable, and type-safe without introducing regressions or deleting hidden domain logic.

## Refactoring Core Directives

- **No Blind Rewrites**: Do not delete existing code blocks and replace them with completely fresh logic unless explicitly ordered. Preserve the implicit logic layout.
- **Test-Driven Refactoring**: Before changing any functional logic, analyze the current execution behavior. If unit tests are missing, help construct behavioral baseline tests to capture the existing state.
- **Logical Equivalence**: Every refactor step must result in strict behavioral equivalence. Inputs, successful outputs, and edge-case exceptions must remain fully aligned with the legacy state.
- **Incremental Transformations**: Break massive refactoring concepts into distinct, atomic sub-steps. Do not refactor multiple unrelated files or layers simultaneously.

## Step-by-Step Modernization Protocol

Follow this strict sequence for every refactoring task:

### Step 1: Behavior Extraction & Analysis
- Read the entire block of legacy code thoroughly. Document all implicit side effects, mutations, default fallback fallthroughs, and structural validation assumptions.
- Identify tightly coupled external dependencies (e.g., global state variables, active database transactions, or direct I/O layers).

### Step 2: Isolation & Dependency Injection
- Decouple hardcoded external configurations or initializations out of the main routine.
- Abstract global variables or external calls behind explicit function arguments or simple interface dependencies so they can be mocked cleanly.

### Step 3: Atomic Modernization Updates
- Gradually introduce modern features (e.g., converting synchronous blocking patterns into clean `async/await`, migrating untyped arguments into strict types, or updating obsolete syntax to modern standards).
- Keep data transformations isolated inside explicit, predictable pure helper functions.

### Step 4: Verification Loop
- Execute the baseline test suites after every micro-step to ensure complete functional integrity remains intact.
- Check whether logging, monitoring details, or precise domain exception responses are preserved across the new implementation.

## Code Quality & Anti-Patterns to Prevent
- **Do not hide exceptions**: Never wrap legacy blocks in wide, blind `try/except` fields that swallow structural bugs or swallow logging information.
- **Do not fix unrelated issues simultaneously**: If you discover syntax style discrepancies, performance bottlenecks, or unrelated bugs while refactoring, document them clearly as separate items instead of modifying the code path mid-task.
- **Keep naming historical continuity**: Retain domain-specific naming terminology unless it directly conflicts with overall legibility or systemic architecture requirements.

What is this CLAUDE.md template for?

This CLAUDE.md template forces your AI coding assistant to abandon the risky "wipe and rewrite" habit. When dealing with complex legacy code, AI models frequently try to rewrite whole functions from scratch, which inadvertently deletes critical edge-case handling or hidden business assumptions accumulated over years.

This blueprint enforces a strict, incremental refactoring lifecycle. It instructs the assistant to map code behavior, write baseline tests first, isolate dependencies, and execute small, logically equivalent transformations that preserve system correctness at every step.

When to use this template

Use this template when untangling undocumented legacy systems, moving untyped code into strict types, rewriting structural components, extracting domain logic from massive controllers into separate services, or converting synchronous I/O operations into high-throughput asynchronous loops.

Recommended engineering refactor flow

[Identify Module] 
       │
       ▼
[Characterize Behavior] ──► (Capture inputs, outputs, exceptions)
       │
       ▼
[Write Baseline Tests]  ──► (Lock in current behavior state)
       │
       ▼
[Incremental Refactor]  ──► (Small, equivalent code updates)
       │
       ▼
[Regression Check]     ──► (Run tests to verify zero behavior drift)

CLAUDE.md Template

# CLAUDE.md: Safe Legacy Refactoring & Modernization Guide

You are operating as an Expert Systems Modernization Engineer specializing in high-reliability refactoring, code untangling, and technical debt reduction.

Your primary objective is to make code clean, maintainable, and type-safe without introducing regressions or deleting hidden domain logic.

## Refactoring Core Directives

- **No Blind Rewrites**: Do not delete existing code blocks and replace them with completely fresh logic unless explicitly ordered. Preserve the implicit logic layout.
- **Test-Driven Refactoring**: Before changing any functional logic, analyze the current execution behavior. If unit tests are missing, help construct behavioral baseline tests to capture the existing state.
- **Logical Equivalence**: Every refactor step must result in strict behavioral equivalence. Inputs, successful outputs, and edge-case exceptions must remain fully aligned with the legacy state.
- **Incremental Transformations**: Break massive refactoring concepts into distinct, atomic sub-steps. Do not refactor multiple unrelated files or layers simultaneously.

## Step-by-Step Modernization Protocol

Follow this strict sequence for every refactoring task:

### Step 1: Behavior Extraction & Analysis
- Read the entire block of legacy code thoroughly. Document all implicit side effects, mutations, default fallback fallthroughs, and structural validation assumptions.
- Identify tightly coupled external dependencies (e.g., global state variables, active database transactions, or direct I/O layers).

### Step 2: Isolation & Dependency Injection
- Decouple hardcoded external configurations or initializations out of the main routine.
- Abstract global variables or external calls behind explicit function arguments or simple interface dependencies so they can be mocked cleanly.

### Step 3: Atomic Modernization Updates
- Gradually introduce modern features (e.g., converting synchronous blocking patterns into clean `async/await`, migrating untyped arguments into strict types, or updating obsolete syntax to modern standards).
- Keep data transformations isolated inside explicit, predictable pure helper functions.

### Step 4: Verification Loop
- Execute the baseline test suites after every micro-step to ensure complete functional integrity remains intact.
- Check whether logging, monitoring details, or precise domain exception responses are preserved across the new implementation.

## Code Quality & Anti-Patterns to Prevent
- **Do not hide exceptions**: Never wrap legacy blocks in wide, blind `try/except` fields that swallow structural bugs or swallow logging information.
- **Do not fix unrelated issues simultaneously**: If you discover syntax style discrepancies, performance bottlenecks, or unrelated bugs while refactoring, document them clearly as separate items instead of modifying the code path mid-task.
- **Keep naming historical continuity**: Retain domain-specific naming terminology unless it directly conflicts with overall legibility or systemic architecture requirements.

Why this template matters

Refactoring legacy code with AI can easily backfire if the model hallucinates or oversimplifies historical logic structures. An unguided AI model will prioritize aesthetic cleanliness over behavioral correctness, resulting in subtle production bugs that are incredibly hard to trace.

This template locks your AI partner into an engineering mindset focused on preserving functionality. It forces the creation of verification steps, safeguards hidden edge cases, and scales technical modernizations cleanly without disrupting system operations.

Recommended additions

  • Incorporate specific linting or structural health metrics (e.g., target cyclomatic complexity limits) to track during code updates.
  • Add specialized rules for decoupling old database ORM behaviors or handling raw SQL queries safely.
  • Define step-by-step instructions for extracting feature flags to enable safe runtime canary testing of refactored logic paths.
  • Incorporate specific snapshot testing procedures for verifying heavy API response data structures.

FAQ

How does this template ensure that old business logic isn't lost?

It explicitly forbids the AI assistant from performing blind rewrites. It requires a behavior analysis step and the installation of baseline regression tests before any functional code code shifts.

Can this template be used to refactor sync code to async Python or Node?

Yes. The modernization rules explicitly define the steps to carefully wrap, extract, and convert blocking synchronous execution blocks into fully non-blocking asynchronous architectures.

What should I do if the legacy code is completely untestable initially?

The template guides the AI assistant through Step 2 (Isolation), helping you extract tightly coupled global calls or hard I/O and turn them into mockable interfaces so testing becomes possible.

Will this slow down the AI's generation speed?

It changes the AI's focus from rapid, large code replacements to producing highly structured, methodical, and safe adjustments, which dramatically cuts down on your manual tracking and debugging time.

About the author

Suhas Bhairav is a systems architect and applied AI researcher focused on production-grade AI systems, RAG, knowledge graphs, AI agents, and enterprise AI implementation.