Code Migration
The Iron Rule
ASSESS BEFORE PLANNING. PLAN BEFORE CODING. TEST BEFORE CUTTING OVER.
Never start migrating code without completing the assessment phase. Skipping assessment leads to mid-migration surprises that blow timelines.
Phase 1: Migration Assessment
Step 1 — Quantify Scope
# Gather hard numbers before estimating anything
find src/ -type f | wc -l # Total files
cloc src/ --quiet # LOC by language
grep -r "import\|require" src/ | wc -l # Dependency touchpoints
find src/ -name "*.test.*" -o -name "*_test.*" | wc -l # Test coverage proxy
Step 2 — Score Complexity (1–5 per factor)
| Factor |
1 (Low) |
3 (Medium) |
5 (High) |
| Size |
<20 files, <2k LOC |
20-100 files, 2-20k LOC |
>100 files, >20k LOC |
| Coupling |
Loose modules, clear interfaces |
Some shared state, moderate coupling |
Tight coupling, global state, circular deps |
| Dependencies |
Few third-party libs, all have equivalents |
Some libs need replacement or adaptation |
Core libs have no equivalent, custom forks |
| Business Logic |
Simple CRUD, straightforward rules |
Moderate domain logic, some edge cases |
Complex rules, financial calcs, compliance |
| Data |
Schema unchanged or trivial mapping |
Schema changes needed, data transformable |
Schema redesign, lossy transformations, large volumes |
Total score: Sum ÷ 5 → complexity rating. <2 = simple, 2–3.5 = moderate, >3.5 = complex.
Step 3 — Identify Risk Patterns
Scan the codebase for patterns that cause migration failures:
| Risk Pattern |
What to Look For |
Why It's Dangerous |
| Global/shared state |
global, window.*=, singletons |
Hidden dependencies between modules |
| Dynamic dispatch |
eval, getattr, monkey-patching |
Can't statically trace call graph |
| Platform-specific code |
OS calls, browser APIs, native modules |
May not have equivalents on target |
| Implicit behavior |
Convention-based routing, magic methods |
Easy to miss during migration |
| Serialized data |
Pickle, Marshal, binary formats |
Format may not survive version change |
Step 4 — Produce Assessment Document
## Migration Assessment: [Source] → [Target]
**Complexity Score**: X.X / 5.0
**Estimated Effort**: [range] person-weeks
**Risk Level**: Low / Medium / High
### Scope
- Files affected: N
- LOC to migrate: N
- Dependencies to replace: N (list them)
- Test coverage: X% (measured, not guessed)
### Critical Risks
1. [Risk] — Impact: [what breaks] — Mitigation: [strategy]
### Dependencies Without Direct Equivalents
| Source Dependency | Purpose | Target Replacement | Effort |
|---|---|---|---|
### Unresolved Questions
- [List every ambiguity — do NOT proceed with assumptions]
If ANY unresolved questions exist: present the assessment and ask before proceeding to Phase 2.
Phase 2: Strategy Selection
Pick ONE strategy. Do not combine them.
| Strategy |
When to Use |
Trade-off |
| Strangler Fig |
Large codebase, can run old+new side by side |
Slower but lowest risk — migrate piece by piece behind a facade |
| Branch by Abstraction |
Shared codebase, can't run two versions |
Introduce abstraction layer, swap implementations underneath |
| Big Bang |
Small codebase (<20 files) or forced by breaking changes |
Fast but high risk — everything migrates at once |
| Parallel Run |
Data pipelines, APIs where correctness is critical |
Run both, compare outputs, cut over when equivalent |
Strangler Fig Implementation Pattern
1. Identify a boundary (API endpoint, page, module)
2. Build new version behind the boundary
3. Route traffic/calls to new version
4. Verify equivalence (tests, monitoring, shadow traffic)
5. Remove old version
6. Repeat for next boundary
Phase 3: Migration Plan
Simple Migration (complexity < 2.5)
| Phase |
Duration |
Tasks |
| Preparation |
1 week |
Setup project, install deps, configure build, write comparison tests |
| Core Migration |
2-3 weeks |
Migrate module by module, run tests after each |
| Validation |
1 week |
Full test suite, performance comparison, edge cases |
Complex Migration (complexity ≥ 2.5)
| Phase |
Duration |
Tasks |
| Foundation |
2 weeks |
Architecture design, PoC for riskiest component, tool selection |
| Infrastructure |
2-3 weeks |
Build pipeline, abstraction layers, dual runtime support |
| Incremental |
6-12 weeks |
Module-by-module migration with comparison tests after each |
| Cutover |
2 weeks |
Remove legacy code, optimize, final validation, rollback drill |
Migration Order
Migrate in dependency order — leaves first, roots last:
1. Utilities / helpers (no internal dependencies)
2. Data models / types
3. Business logic modules
4. Integration layers (APIs, database, external services)
5. UI / presentation layer
6. Configuration and build system
Phase 4: Testing Strategy
Comparison Tests (Write These FIRST)
Before migrating any module, write tests that capture current behavior:
1. Identify public API of the module (functions, endpoints, events)
2. Write tests against the OLD code that assert current behavior
3. Run tests — they must pass on old code
4. Migrate the module
5. Run the SAME tests against new code — they must still pass
This catches behavioral regressions that unit tests miss.
Test Categories
| Category |
What It Catches |
When to Run |
| Comparison tests |
Behavioral regression |
After each module migration |
| Unit tests |
Logic errors in new code |
During development |
| Integration tests |
Cross-module compatibility |
After each migration phase |
| Performance tests |
Latency/throughput regression |
Before and after cutover |
| Data validation |
Data integrity issues |
During and after data migration |
Phase 5: Rollback
Rollback Triggers — Decide These BEFORE Migrating
| Condition |
Threshold |
Detection |
| Critical functionality broken |
Any P0 feature fails |
Automated smoke tests |
| Performance degradation |
>50% latency increase at p95 |
APM dashboard |
| Data corruption |
Any integrity check failure |
Validation job |
| Error rate spike |
>5% increase over baseline |
Error tracking |
Rollback Procedures by Strategy
| Strategy |
Rollback Method |
Time to Rollback |
| Strangler Fig |
Route traffic back to old module |
Seconds (config change) |
| Branch by Abstraction |
Swap implementation back |
Minutes (deploy) |
| Big Bang |
Deploy previous version |
Minutes (CI/CD rollback) |
| Feature Flag |
Toggle flag off |
Seconds |
Large-Scale Migration
For large codebases (>50 files affected), organize migration into independent module batches:
- Group files by module/package — each batch must be independently migratable
- Process batches sequentially — migrate one module at a time
- After each batch: run tests, verify no regressions, commit
- After all batches: run full test suite, verify cross-module interactions
Deliverables Checklist
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: code-migration3description: Codebase migration between frameworks, languages, versions, or platforms with assessment, planning, and rollback patterns. Use when migrating codebases between frameworks, languages, versions, or platforms. Provides migration assessment patterns, planning templates, strategy selection, testing strategies, rollback procedures, and automation approaches. Do NOT use for dependency version upgrades (use dependency-upgrade). Use when this capability is needed.4---56# Code Migration78## The Iron Rule910```11ASSESS BEFORE PLANNING. PLAN BEFORE CODING. TEST BEFORE CUTTING OVER.12```1314Never start migrating code without completing the assessment phase. Skipping assessment leads to mid-migration surprises that blow timelines.1516## Phase 1: Migration Assessment1718### Step 1 — Quantify Scope1920```bash21# Gather hard numbers before estimating anything22find src/ -type f | wc -l # Total files23cloc src/ --quiet # LOC by language24grep -r "import\|require" src/ | wc -l # Dependency touchpoints25find src/ -name "*.test.*" -o -name "*_test.*" | wc -l # Test coverage proxy26```2728### Step 2 — Score Complexity (1–5 per factor)2930| Factor | 1 (Low) | 3 (Medium) | 5 (High) |31|--------|---------|------------|----------|32| **Size** | <20 files, <2k LOC | 20-100 files, 2-20k LOC | >100 files, >20k LOC |33| **Coupling** | Loose modules, clear interfaces | Some shared state, moderate coupling | Tight coupling, global state, circular deps |34| **Dependencies** | Few third-party libs, all have equivalents | Some libs need replacement or adaptation | Core libs have no equivalent, custom forks |35| **Business Logic** | Simple CRUD, straightforward rules | Moderate domain logic, some edge cases | Complex rules, financial calcs, compliance |36| **Data** | Schema unchanged or trivial mapping | Schema changes needed, data transformable | Schema redesign, lossy transformations, large volumes |3738**Total score**: Sum ÷ 5 → complexity rating. <2 = simple, 2–3.5 = moderate, >3.5 = complex.3940### Step 3 — Identify Risk Patterns4142Scan the codebase for patterns that cause migration failures:4344| Risk Pattern | What to Look For | Why It's Dangerous |45|-------------|------------------|--------------------|46| Global/shared state | `global`, `window.*=`, singletons | Hidden dependencies between modules |47| Dynamic dispatch | `eval`, `getattr`, monkey-patching | Can't statically trace call graph |48| Platform-specific code | OS calls, browser APIs, native modules | May not have equivalents on target |49| Implicit behavior | Convention-based routing, magic methods | Easy to miss during migration |50| Serialized data | Pickle, Marshal, binary formats | Format may not survive version change |5152### Step 4 — Produce Assessment Document5354```markdown55## Migration Assessment: [Source] → [Target]5657**Complexity Score**: X.X / 5.058**Estimated Effort**: [range] person-weeks59**Risk Level**: Low / Medium / High6061### Scope62- Files affected: N63- LOC to migrate: N64- Dependencies to replace: N (list them)65- Test coverage: X% (measured, not guessed)6667### Critical Risks681. [Risk] — Impact: [what breaks] — Mitigation: [strategy]6970### Dependencies Without Direct Equivalents71| Source Dependency | Purpose | Target Replacement | Effort |72|---|---|---|---|7374### Unresolved Questions75- [List every ambiguity — do NOT proceed with assumptions]76```7778**If ANY unresolved questions exist: present the assessment and ask before proceeding to Phase 2.**7980## Phase 2: Strategy Selection8182Pick ONE strategy. Do not combine them.8384| Strategy | When to Use | Trade-off |85|----------|-------------|-----------|86| **Strangler Fig** | Large codebase, can run old+new side by side | Slower but lowest risk — migrate piece by piece behind a facade |87| **Branch by Abstraction** | Shared codebase, can't run two versions | Introduce abstraction layer, swap implementations underneath |88| **Big Bang** | Small codebase (<20 files) or forced by breaking changes | Fast but high risk — everything migrates at once |89| **Parallel Run** | Data pipelines, APIs where correctness is critical | Run both, compare outputs, cut over when equivalent |9091### Strangler Fig Implementation Pattern9293```941. Identify a boundary (API endpoint, page, module)952. Build new version behind the boundary963. Route traffic/calls to new version974. Verify equivalence (tests, monitoring, shadow traffic)985. Remove old version996. Repeat for next boundary100```101102## Phase 3: Migration Plan103104### Simple Migration (complexity < 2.5)105106| Phase | Duration | Tasks |107|-------|----------|-------|108| Preparation | 1 week | Setup project, install deps, configure build, write comparison tests |109| Core Migration | 2-3 weeks | Migrate module by module, run tests after each |110| Validation | 1 week | Full test suite, performance comparison, edge cases |111112### Complex Migration (complexity ≥ 2.5)113114| Phase | Duration | Tasks |115|-------|----------|-------|116| Foundation | 2 weeks | Architecture design, PoC for riskiest component, tool selection |117| Infrastructure | 2-3 weeks | Build pipeline, abstraction layers, dual runtime support |118| Incremental | 6-12 weeks | Module-by-module migration with comparison tests after each |119| Cutover | 2 weeks | Remove legacy code, optimize, final validation, rollback drill |120121### Migration Order122123Migrate in dependency order — leaves first, roots last:124125```1261. Utilities / helpers (no internal dependencies)1272. Data models / types1283. Business logic modules1294. Integration layers (APIs, database, external services)1305. UI / presentation layer1316. Configuration and build system132```133134## Phase 4: Testing Strategy135136### Comparison Tests (Write These FIRST)137138Before migrating any module, write tests that capture current behavior:139140```1411. Identify public API of the module (functions, endpoints, events)1422. Write tests against the OLD code that assert current behavior1433. Run tests — they must pass on old code1444. Migrate the module1455. Run the SAME tests against new code — they must still pass146```147148This catches behavioral regressions that unit tests miss.149150### Test Categories151152| Category | What It Catches | When to Run |153|----------|----------------|-------------|154| Comparison tests | Behavioral regression | After each module migration |155| Unit tests | Logic errors in new code | During development |156| Integration tests | Cross-module compatibility | After each migration phase |157| Performance tests | Latency/throughput regression | Before and after cutover |158| Data validation | Data integrity issues | During and after data migration |159160## Phase 5: Rollback161162### Rollback Triggers — Decide These BEFORE Migrating163164| Condition | Threshold | Detection |165|-----------|-----------|-----------|166| Critical functionality broken | Any P0 feature fails | Automated smoke tests |167| Performance degradation | >50% latency increase at p95 | APM dashboard |168| Data corruption | Any integrity check failure | Validation job |169| Error rate spike | >5% increase over baseline | Error tracking |170171### Rollback Procedures by Strategy172173| Strategy | Rollback Method | Time to Rollback |174|----------|----------------|------------------|175| Strangler Fig | Route traffic back to old module | Seconds (config change) |176| Branch by Abstraction | Swap implementation back | Minutes (deploy) |177| Big Bang | Deploy previous version | Minutes (CI/CD rollback) |178| Feature Flag | Toggle flag off | Seconds |179180## Large-Scale Migration181182For large codebases (>50 files affected), organize migration into independent module batches:1831841. Group files by module/package — each batch must be independently migratable1852. Process batches sequentially — migrate one module at a time1863. After each batch: run tests, verify no regressions, commit1874. After all batches: run full test suite, verify cross-module interactions188189## Deliverables Checklist190191- [ ] Migration assessment with complexity score192- [ ] Strategy selection with rationale193- [ ] Phased migration plan with timeline194- [ ] Comparison tests for each module (written before migration)195- [ ] Rollback triggers and procedures defined196- [ ] Progress tracking per module197198---199> Converted and distributed by [TomeVault](https://tomevault.io/claim/jlaws) — claim your Tome and manage your conversions.200<!-- tomevault:4.0:skill_md:2026-04-13 -->