Code Migration
Migration Assessment
Complexity Factors
| Factor |
Considerations |
| Size |
File count, LOC, component count |
| Architectural |
Coupling, layer separation, pattern usage |
| Dependency |
Third-party libs, version constraints, compatibility |
| Business Logic |
Complexity of rules, domain knowledge needed |
| Data |
Schema migrations, data transformations, integrity |
Risk Patterns to Scan
risk_patterns = {
'global_state': { 'pattern': r'(global|window)\.\w+\s*=', 'severity': 'high' },
'direct_dom': { 'pattern': r'document\.(getElementById|querySelector)', 'severity': 'medium' },
'async_patterns': { 'pattern': r'(callback|setTimeout|setInterval)', 'severity': 'medium' },
'deprecated_apis': { 'pattern': r'(componentWillMount|componentWillReceiveProps)', 'severity': 'high' }
}
Migration Planning
Simple Migration (complexity < 3):
| Phase |
Duration |
Tasks |
| Preparation |
1 week |
Setup project, install deps, configure build, setup testing |
| Core Migration |
2-3 weeks |
Migrate utilities, port components, update models, migrate logic |
| Testing |
1 week |
Unit, integration, performance testing, bug fixes |
Complex Migration (complexity >= 3):
| Phase |
Duration |
Tasks |
| Foundation |
2 weeks |
Architecture design, PoC, tool selection, team training |
| Infrastructure |
3 weeks |
Build pipeline, dev environment, core abstractions |
| Incremental |
6-8 weeks |
Feature modules, adapters/bridges, dual runtime |
| Cutover |
2 weeks |
Complete remaining, remove legacy, optimize, final testing |
Framework Migration: React to Vue
// JSX to Template conversions
template = template.replace(/className=/g, 'class=');
template = template.replace(/onClick={/g, '@click="');
template = template.replace(/{(\w+) && (.+?)}/g, '<template v-if="$1">$2</template>');
template = template.replace(/{(\w+)\.map\(.*?\)}/g, '<template v-for="...">...</template>');
// Lifecycle mapping
lifecycleMapping = {
'componentDidMount': 'mounted',
'componentDidUpdate': 'updated',
'componentWillUnmount': 'beforeDestroy',
'getDerivedStateFromProps': 'computed'
};
Framework Migration: Python 2 to 3
# Key transformations
'.iteritems()' -> '.items()'
'.iterkeys()' -> '.keys()'
'xrange' -> 'range'
'.has_key(' -> ' in '
'print statement' -> 'print()'
'print >> file,' -> 'print(..., file=file)'
Framework Migration: REST to GraphQL
// Map REST endpoints to GraphQL
// GET /resources -> Query { resources }
// POST /resources -> Mutation { createResource }
// PUT /resources/:id -> Mutation { updateResource }
// DELETE /resources/:id -> Mutation { deleteResource }
Database: SQL to NoSQL
# Design decisions for document structure
for rel in relationships:
if rel['type'] == 'one-to-one' or should_embed(rel):
# Embed related data in document
structure['embedded'].append(rel)
else:
# Store reference (foreign key equivalent)
structure['references'].append(rel)
# Batch migration pattern
async def migrate_table(table, mapping):
async for batch in read_in_batches(table, batch_size=1000):
documents = [transform_row_to_document(row, mapping) for row in batch]
await nosql[mapping['collection']].insert_many(documents)
Rollback Triggers
| Condition |
Threshold |
Detection |
| Critical functionality broken |
Any P0 feature |
Automated monitoring |
| Performance degradation |
>50% response time increase |
APM metrics |
| Data corruption |
Any integrity issues |
Data validation checks |
| High error rate |
>5% error rate increase |
Error tracking |
Rollback by Strategy
- Blue-Green: Switch load balancer back to blue environment
- Canary: Shift traffic back to stable version
- Feature Flag: Toggle flag off, monitor recovery
Key Deliverables Checklist
Agent Team Mode
For large codebases (>50 files affected) or multi-module migrations where independent subsystems can be migrated in parallel.
Team Configuration
team:
recommended_size: 3-5
agent_roles:
- name: module-migrator-N
type: general-purpose
focus: "Migrate assigned module/subsystem independently"
skills_loaded: ["migration:code-migration"]
- name: migration-reviewer
type: Explore
focus: "Validate each migration against comparison tests and compatibility"
skills_loaded: ["migration:code-migration", "testing:language-testing-patterns"]
file_ownership: "by-module"
lead_mode: "delegate"
Team Workflow
- Lead runs Migration Assessment phase — complexity analysis, dependency graph, risk patterns
- Lead creates phased plan, assigns independent modules to module-migrator teammates
- Each module-migrator owns their file set exclusively — no cross-module edits
- migration-reviewer validates each completed module (tests pass, API compatibility, no regressions)
- Lead handles integration phase — cross-module wiring, full test suite, rollback preparation
File Ownership Example
module-migrator-1:
files: src/auth/**
constraint: Do NOT modify files outside this path
module-migrator-2:
files: src/payments/**
constraint: Do NOT modify files outside this path
Single-Agent Fallback
Without team mode, execute all phases sequentially (default behavior). Team mode is an optional enhancement.
1---2name: code-migration-23description: Use when migrating codebases between frameworks, languages, versions, or platforms. Provides migration assessment patterns, planning templates, framework-specific migration examples, testing strategies, rollback procedures, and automation approaches.4---5
6# Code Migration
7
8## Migration Assessment
9
10### Complexity Factors
11
12| Factor | Considerations |
13|--------|---------------|
14| Size | File count, LOC, component count |
15| Architectural | Coupling, layer separation, pattern usage |
16| Dependency | Third-party libs, version constraints, compatibility |
17| Business Logic | Complexity of rules, domain knowledge needed |
18| Data | Schema migrations, data transformations, integrity |
19
20### Risk Patterns to Scan
21
22```python
23risk_patterns = {
24 'global_state': { 'pattern': r'(global|window)\.\w+\s*=', 'severity': 'high' },
25 'direct_dom': { 'pattern': r'document\.(getElementById|querySelector)', 'severity': 'medium' },
26 'async_patterns': { 'pattern': r'(callback|setTimeout|setInterval)', 'severity': 'medium' },
27 'deprecated_apis': { 'pattern': r'(componentWillMount|componentWillReceiveProps)', 'severity': 'high' }
28}
29```
30
31## Migration Planning
32
33**Simple Migration (complexity < 3)**:
34
35| Phase | Duration | Tasks |
36|-------|----------|-------|
37| Preparation | 1 week | Setup project, install deps, configure build, setup testing |
38| Core Migration | 2-3 weeks | Migrate utilities, port components, update models, migrate logic |
39| Testing | 1 week | Unit, integration, performance testing, bug fixes |
40
41**Complex Migration (complexity >= 3)**:
42
43| Phase | Duration | Tasks |
44|-------|----------|-------|
45| Foundation | 2 weeks | Architecture design, PoC, tool selection, team training |
46| Infrastructure | 3 weeks | Build pipeline, dev environment, core abstractions |
47| Incremental | 6-8 weeks | Feature modules, adapters/bridges, dual runtime |
48| Cutover | 2 weeks | Complete remaining, remove legacy, optimize, final testing |
49
50## Framework Migration: React to Vue
51
52```javascript
53// JSX to Template conversions
54template = template.replace(/className=/g, 'class=');
55template = template.replace(/onClick={/g, '@click="');
56template = template.replace(/{(\w+) && (.+?)}/g, '<template v-if="$1">$2</template>');
57template = template.replace(/{(\w+)\.map\(.*?\)}/g, '<template v-for="...">...</template>');
58
59// Lifecycle mapping
60lifecycleMapping = {
61 'componentDidMount': 'mounted',
62 'componentDidUpdate': 'updated',
63 'componentWillUnmount': 'beforeDestroy',
64 'getDerivedStateFromProps': 'computed'
65};
66```
67
68## Framework Migration: Python 2 to 3
69
70```python
71# Key transformations
72'.iteritems()' -> '.items()'
73'.iterkeys()' -> '.keys()'
74'xrange' -> 'range'
75'.has_key(' -> ' in '
76'print statement' -> 'print()'
77'print >> file,' -> 'print(..., file=file)'
78```
79
80## Framework Migration: REST to GraphQL
81
82```javascript
83// Map REST endpoints to GraphQL
84// GET /resources -> Query { resources }
85// POST /resources -> Mutation { createResource }
86// PUT /resources/:id -> Mutation { updateResource }
87// DELETE /resources/:id -> Mutation { deleteResource }
88```
89
90## Database: SQL to NoSQL
91
92```python
93# Design decisions for document structure
94for rel in relationships:
95 if rel['type'] == 'one-to-one' or should_embed(rel):
96 # Embed related data in document
97 structure['embedded'].append(rel)
98 else:
99 # Store reference (foreign key equivalent)
100 structure['references'].append(rel)
101
102# Batch migration pattern
103async def migrate_table(table, mapping):
104 async for batch in read_in_batches(table, batch_size=1000):
105 documents = [transform_row_to_document(row, mapping) for row in batch]
106 await nosql[mapping['collection']].insert_many(documents)
107```
108
109## Rollback Triggers
110
111| Condition | Threshold | Detection |
112|-----------|-----------|-----------|
113| Critical functionality broken | Any P0 feature | Automated monitoring |
114| Performance degradation | >50% response time increase | APM metrics |
115| Data corruption | Any integrity issues | Data validation checks |
116| High error rate | >5% error rate increase | Error tracking |
117
118### Rollback by Strategy
119
120- **Blue-Green**: Switch load balancer back to blue environment
121- **Canary**: Shift traffic back to stable version
122- **Feature Flag**: Toggle flag off, monitor recovery
123
124## Key Deliverables Checklist
125
126- [ ] Migration analysis of source codebase
127- [ ] Risk assessment with mitigation strategies
128- [ ] Phased migration plan with timeline
129- [ ] Automated migration scripts
130- [ ] Comparison tests and validation
131- [ ] Rollback procedures
132- [ ] Progress tracking and monitoring
133
134## Agent Team Mode
135
136For large codebases (>50 files affected) or multi-module migrations where independent subsystems can be migrated in parallel.
137
138### Team Configuration
139
140```yaml
141team:
142 recommended_size: 3-5
143 agent_roles:
144 - name: module-migrator-N
145 type: general-purpose
146 focus: "Migrate assigned module/subsystem independently"
147 skills_loaded: ["migration:code-migration"]
148 - name: migration-reviewer
149 type: Explore
150 focus: "Validate each migration against comparison tests and compatibility"
151 skills_loaded: ["migration:code-migration", "testing:language-testing-patterns"]
152 file_ownership: "by-module"
153 lead_mode: "delegate"
154```
155
156### Team Workflow
157
1581. Lead runs Migration Assessment phase — complexity analysis, dependency graph, risk patterns
1592. Lead creates phased plan, assigns independent modules to module-migrator teammates
1603. Each module-migrator owns their file set exclusively — no cross-module edits
1614. migration-reviewer validates each completed module (tests pass, API compatibility, no regressions)
1625. Lead handles integration phase — cross-module wiring, full test suite, rollback preparation
163
164### File Ownership Example
165
166```
167module-migrator-1:
168 files: src/auth/**
169 constraint: Do NOT modify files outside this path
170
171module-migrator-2:
172 files: src/payments/**
173 constraint: Do NOT modify files outside this path
174```
175
176### Single-Agent Fallback
177
178Without team mode, execute all phases sequentially (default behavior). Team mode is an optional enhancement.