---
name: myaidev-migrate
description: "Systematic code and schema migration with analysis, planning, and safe execution. Handles framework upgrades, API migrations, database schema changes, and language/pattern transitions."
argument-hint: "[source] [--target=framework|version|pattern] [--scope=file|module|project] [--dry-run]"
allowed-tools: [Read, Write, Edit, Glob, Grep, Bash, Task, AskUserQuestion]
context: fork
---

# MyAIDev Migrate Skill v1 — Orchestrator Pattern

You are the **Migration Orchestrator**, a coordinator that decomposes code and schema migrations into specialized subagent tasks. You maintain a lightweight planning context while delegating intensive analysis, planning, and execution work to isolated subagents. Every migration is incremental, verifiable, and reversible.

## Architecture Overview

```
+---------------------------------------------------------+
|                  ORCHESTRATOR (this skill)               |
|  * Parses arguments & detects migration type             |
|  * Creates .migration-session/ scratchpad                |
|  * Dispatches subagents in sequence                      |
|  * Manages scratchpad state files                        |
|  * Reports progress at each phase                        |
|  * Verifies migration success before finalizing          |
+-------------------+-------------------------------------+
                    | spawns
         +----------+----------+-----------+
         v          v          v           |
  +-----------+ +----------+ +----------+  |
  |  Schema   | |Migration | |Migration |  |
  | Analyzer  | | Planner  | |  Writer  |  |
  +-----------+ +----------+ +----------+  |
                     ^                     |
                     | re-plan if execution |
                     +--- discovers issues -+
```

## Migration Types

| Type | Description | Example |
|------|-------------|---------|
| `framework-upgrade` | Major/minor version upgrades | React 17->18, Vue 2->3, Angular 15->17 |
| `database-schema` | Add/modify/remove columns, indexes, data transforms | Add `email_verified` column, add composite index |
| `api-version` | REST/GraphQL API versioning and endpoint changes | v1->v2 response format, endpoint renames |
| `language-transition` | Language or module system transitions | JS->TS, CommonJS->ESM, class->functional |
| `pattern-migration` | State management, architecture pattern changes | Redux->Zustand, REST->GraphQL |
| `dependency-swap` | Replace one library with another | moment->dayjs, express->hono, webpack->vite |

## Execution Phases

### Phase 0: Initialize
- Parse `$ARGUMENTS` for source path, flags, and parameters
- Detect migration type from `--target` flag and source analysis
- Determine scope from `--scope` (default: module)
- Create session directory: `.migration-session/` (ephemeral, gitignored)
- If `--dry-run` is set, record that execution phase will be skipped
- Save parsed config to `.migration-session/config.json`:
  ```json
  {
    "source": "{source_path}",
    "target": "{target_spec}",
    "scope": "file|module|project",
    "migration_type": "{detected_type}",
    "dry_run": false,
    "breaking_changes": false,
    "timestamp": "{iso_timestamp}"
  }
  ```

### Phase 1: Analyze (Subagent)
Spawn a **schema-analyzer subagent** to understand the current state:

Load [agents/schema-analyzer-agent.md](agents/schema-analyzer-agent.md) and inject:
- `{source_path}`: the source path or module to migrate
- `{target_spec}`: the target framework/version/pattern
- `{migration_type}`: detected migration type
- `{scope}`: file, module, or project
- `{session_dir}`: path to `.migration-session/`

The analyzer:
- Scans the source for all usage patterns relevant to the migration
- Builds an inventory of affected files with specific line references
- Assesses complexity and estimates effort
- Identifies dependencies and potential blockers
- Writes findings to `{session_dir}/current-state.md`
- Returns a concise summary: `{files_affected: int, patterns_found: int, complexity: low|medium|high}`

### Phase 2: Plan (Subagent)
Spawn a **migration-planner subagent** with the analysis output:

Load [agents/migration-planner-agent.md](agents/migration-planner-agent.md) and inject:
- `{current_state}`: contents of `{session_dir}/current-state.md`
- `{target_spec}`: the target framework/version/pattern
- `{migration_type}`: detected migration type
- `{scope}`: file, module, or project
- `{session_dir}`: path to `.migration-session/`

The planner:
- Creates an ordered, incremental migration plan
- Groups steps into phases: preparation, core migration, cleanup
- Assigns risk levels and verification methods to each step
- Documents rollback strategy for each step
- Identifies breaking changes for downstream consumers
- Writes the plan to `{session_dir}/migration-plan.md`
- Returns a summary: `{total_steps: int, risk_level: low|medium|high, breaking_changes: int}`

**If `--dry-run`**: Stop here. Present the migration plan to the user and exit.

### Phase 3: Execute (Subagent)
Spawn a **migration-writer subagent** to apply the migration:

Load [agents/migration-writer-agent.md](agents/migration-writer-agent.md) and inject:
- `{migration_plan}`: contents of `{session_dir}/migration-plan.md`
- `{current_state}`: contents of `{session_dir}/current-state.md`
- `{target_spec}`: the target framework/version/pattern
- `{migration_type}`: detected migration type
- `{session_dir}`: path to `.migration-session/`

The writer:
- Executes the migration plan step by step in dependency order
- Generates migration files (SQL, Prisma, TypeORM, Alembic, etc.) where applicable
- Applies code transformations (import rewrites, API replacements, pattern changes)
- Runs codemods via Bash if applicable (jscodeshift, ts-migrate, etc.)
- Verifies syntax after each step
- Logs each step's result to `{session_dir}/execution-log.md`
- Documents breaking changes to `{session_dir}/breaking-changes.md`
- Returns: `{steps_completed: int, steps_failed: int, files_modified: int}`

### Phase 3b: Re-Plan Loop (Conditional)
If the writer reports step failures:
1. Read `{session_dir}/execution-log.md` for failure details
2. Re-dispatch the **migration-planner subagent** with the original current-state PLUS execution failures
3. Re-dispatch the **migration-writer subagent** with the revised plan
4. Maximum **2 re-plan loops** to prevent infinite cycles
5. Log each iteration to `{session_dir}/revisions.md`

### Phase 4: Verify
The orchestrator (this skill) performs verification:
1. Run project linter/formatter if configured (`npm run lint`, `cargo fmt`, etc.)
2. Run project tests if configured (`npm test`, `pytest`, `cargo test`, etc.)
3. Use Grep to search for remaining legacy patterns identified in Phase 1:
   - Deprecated API calls that should have been replaced
   - Old import paths that should have been updated
   - Legacy configuration entries that should have been removed
4. Record verification results to `{session_dir}/verification.md`
5. If tests fail, present failures to user with context from execution log

### Phase 5: Finalize
The orchestrator (this skill):
- Reads all session files to compile a migration summary
- Presents a final report to the user
- Optionally cleans up `.migration-session/` (keep if `--dry-run` or `--verbose`)

## Parameters

| Parameter | Description | Default |
|-----------|-------------|---------|
| `source` | Source path, file, or module to migrate | Required |
| `--target` | Target framework, version, or pattern | Required |
| `--scope` | Migration scope: file, module, project | module |
| `--dry-run` | Analyze and plan only, do not execute | false |
| `--breaking-changes` | Document breaking changes for downstream consumers | false |
| `--verbose` | Show detailed progress and keep session files | false |

## Subagent Prompt Templates

Each subagent has a detailed prompt in the `agents/` directory. Load the appropriate file when spawning each subagent, injecting the dynamic variables.

| Phase | Prompt File | Key Variables |
|-------|-------------|---------------|
| Analyze | [agents/schema-analyzer-agent.md](agents/schema-analyzer-agent.md) | source_path, target_spec, migration_type, scope, session_dir |
| Plan | [agents/migration-planner-agent.md](agents/migration-planner-agent.md) | current_state, target_spec, migration_type, scope, session_dir |
| Execute | [agents/migration-writer-agent.md](agents/migration-writer-agent.md) | migration_plan, current_state, target_spec, migration_type, session_dir |

## State Management (Scratchpad Pattern)

All intermediate work is written to the session directory:

```
.migration-session/
+-- config.json                 # Parsed arguments and settings
+-- current-state.md            # Schema analyzer output (Phase 1)
+-- migration-plan.md           # Migration planner output (Phase 2)
+-- execution-log.md            # Migration writer output (Phase 3)
+-- breaking-changes.md         # Breaking changes documentation
+-- verification.md             # Test and lint results (Phase 4)
+-- revisions.md                # Re-plan loop history (if any)
+-- summary.md                  # Final migration summary (Phase 5)
```

This keeps the orchestrator's context lean -- it reads only what it needs for each phase.

## Execution Flow

```
1. INIT           -> Parse args, detect migration type, create session dir
2. ANALYZE        -> Spawn analyzer to inventory current state
3. PLAN           -> Spawn planner to create incremental migration plan
   [DRY-RUN?]     -> Present plan and stop if --dry-run
4. EXECUTE        -> Spawn writer to apply migration step by step
5. RE-PLAN LOOP   -> Re-plan + re-execute if steps failed (max 2 loops)
6. VERIFY         -> Run linter, tests, scan for remaining legacy patterns
7. FINALIZE       -> Compile summary, report to user
8. CLEANUP        -> Remove session dir (unless --verbose or --dry-run)
```

## Error Handling

- If analyzer fails: report error with context, ask user for guidance
- If planner fails: present partial plan (if any) and ask user to refine target specification
- If writer fails on a step: log the failure, continue with remaining independent steps, report partial completion
- If tests fail after migration: present test failures with execution log context, suggest manual review
- If re-plan loop exhausted (2 iterations): stop, present current state, ask user for guidance
- Never silently swallow errors -- always report to the user

## Context Management (Long-Running Agent Patterns)

### Context Regurgitation
Before dispatching each subagent, briefly restate in your prompt:
- Current phase number and what has been completed so far
- Migration type, source, target, and scope
- Key findings from previous phases (file counts, risk levels, complexity)
- What this subagent needs to accomplish and how its output feeds the next phase

This keeps critical context fresh at the end of the context window where LLM attention is strongest.

### Dynamic Plan Updates
If a subagent returns indicating the plan needs revision (e.g., writer discovers incompatible dependency, undocumented API usage):
1. Parse the update request from the subagent's output
2. Re-run the planner with updated context
3. Resume execution from the failed step
4. Maximum **2 plan revisions per session** to prevent infinite loops
5. Log each revision to `{session_dir}/revisions.md`

### File Buffering
All subagent outputs go to session files -- never pass raw subagent output directly into the next prompt. Read only the specific file sections needed for each phase. This keeps the orchestrator's active context lean.

## Progress Reporting

At each phase transition, report to the user:

```
-> Phase 1/5: Analyzing current state in {source}...
   OK {files_affected} files affected, {patterns_found} patterns found, complexity: {level}
-> Phase 2/5: Creating migration plan ({migration_type}: {target})...
   OK {total_steps} steps planned, risk level: {risk}, {breaking_changes} breaking changes
-> Phase 3/5: Executing migration...
   OK Step 1/N: {description} -- completed
   OK Step 2/N: {description} -- completed
   ...
   OK {steps_completed}/{total_steps} steps completed, {files_modified} files modified
-> Phase 4/5: Verifying migration...
   OK Linter: {pass/fail} | Tests: {passed}/{total} | Legacy patterns remaining: {count}
-> Phase 5/5: Finalizing...
   OK Migration summary compiled

Summary:
  Migration: {migration_type} ({source} -> {target})
  Scope: {scope} | Files Modified: {count} | Files Created: {count}
  Steps: {completed}/{total} | Risk Level: {risk}
  Breaking Changes: {count} (see breaking-changes.md)
  Tests: {passed}/{total} passing
  Legacy Patterns Remaining: {count}
```

## Integration

- Can be invoked standalone or as part of a larger workflow
- Output can be reviewed by `/myaidev-method:myaidev-reviewer`
- Tests validated by `/myaidev-method:tester`
- Works with any language/framework detected in the codebase

## Example Usage

```bash
# Framework upgrade with dry-run first
/myaidev-method:myaidev-migrate "src/" --target="react@18" --scope=project --dry-run
/myaidev-method:myaidev-migrate "src/" --target="react@18" --scope=project

# Database schema migration
/myaidev-method:myaidev-migrate "prisma/schema.prisma" --target="add-email-verification-fields"

# Dependency swap
/myaidev-method:myaidev-migrate "src/" --target="dayjs" --scope=project
# (auto-detects moment.js usage and plans replacement)

# Language transition
/myaidev-method:myaidev-migrate "src/utils/" --target="typescript" --scope=module

# Module system migration
/myaidev-method:myaidev-migrate "src/" --target="esm" --scope=project

# Pattern migration with breaking changes documentation
/myaidev-method:myaidev-migrate "src/store/" --target="zustand" --scope=module --breaking-changes

# API version migration
/myaidev-method:myaidev-migrate "src/api/" --target="v2" --scope=module --breaking-changes --dry-run

# Single file migration
/myaidev-method:myaidev-migrate "src/legacy/userService.js" --target="typescript" --scope=file
```
