Automated token migration execution system with dry-run, validation, and rollback capabilities.
The migration executor implements the final step in the B→C migration pipeline:
Audit → Risk Assessment → Scenario Generation → **Execution**
It safely applies migration scenarios to your token system with:
- Dry-run mode (default): Preview changes before applying
- Automated reference updates: Finds and updates all token references
- Validation: Checks integrity, accessibility, and structure post-migration
- Rollback: Create snapshots before execution for easy rollback
- Progress tracking: Detailed reporting of each operation
-
Executor (
executor.ts)- Phase execution orchestration
- Action implementation (rename, merge, split, etc.)
- Reference tracking and updates
- Snapshot/rollback management
-
Scanner (
scanner.ts)- Codebase scanning for token references
- Multi-format support (TS/JS, CSS/SCSS, JSON)
- Pattern matching for different reference styles
- Bulk update capabilities
-
Validator (
validation.ts)- Post-migration validation checks
- Integrity verification (no broken refs, no circular deps)
- Accessibility validation (WCAG contrast preservation)
- Structural analysis (naming conventions, hierarchy)
Execute a migration scenario with safety features enabled by default.
{
"tool": "execute_migration",
"args": {
"scenarioId": "conservative-001",
"phaseNumber": 1,
"dryRun": true,
"createSnapshot": true,
"stopOnError": true,
"skipValidation": false
}
}- scenarioId (optional): ID from
generate_refactor_scenarios. Default: uses conservative approach. - phaseNumber (optional): Execute only this phase. Default: all phases.
- dryRun (optional): Preview mode (no changes applied). DEFAULT: true for safety.
- createSnapshot (optional): Create rollback snapshot. Default: true.
- stopOnError (optional): Stop on first error. Default: true.
- skipValidation (optional): Skip post-execution validation. Default: false.
Markdown report with:
- Phase-by-phase execution status
- Action results (rename, merge, split, etc.)
- Token operation details
- Reference update counts
- Validation results
- Summary statistics
Always start with dry run to see what will change:
{
"tool": "execute_migration",
"args": {
"scenarioId": "conservative-001",
"dryRun": true
}
}Output:
## Phase 1: Fix Critical Issues
✅ Status: completed
Actions: 3 (3 completed, 0 failed)
### Actions
✅ rename (12 targets)
✓ rename: `color.warning.background` → `background.feedback.warning`
Updated 5 reference(s)
✓ rename: `text.error` → `text.feedback.danger`
Updated 8 reference(s)
...
ℹ️ **This was a DRY RUN.** No changes were applied.Execute critical phases first, validate, then continue:
{
"tool": "execute_migration",
"args": {
"scenarioId": "conservative-001",
"phaseNumber": 1,
"dryRun": false,
"createSnapshot": true
}
}Output:
⚠️ LIVE EXECUTION
✅ Snapshot created: snapshot-1234567890
## Phase 1: Fix Critical Issues
✅ Status: completed
Duration: 1250ms
## Post-Execution Validation
✅ Migration Integrity: passed
✅ Reference Validation: passed
⚠️ Naming Convention Compliance: 2 warnings
✅ Structure Validation: passed
✅ Accessibility Validation: passedOnce phases 1-N are validated, execute remaining:
{
"tool": "execute_migration",
"args": {
"scenarioId": "conservative-001",
"dryRun": false
}
}The executor supports these action types:
Renames token and updates all references.
{
type: "rename",
targets: ["color.primary.text"],
newPath: "text.action.default"
}Operations:
- Updates token path in token map
- Finds all references across codebase
- Updates references in all files
- Validates no broken links remain
Combines multiple tokens into one, redirecting all references.
{
type: "merge",
targets: ["color.success", "color.positive"],
newPath: "semantic.feedback.success"
}Operations:
- Picks target token as survivor
- Redirects all source token references to target
- Deletes source tokens
- Validates no orphaned references
Marks token for manual split (creates placeholder).
{
type: "split",
targets: ["color.primary"], // Used for too many purposes
}Operations:
- Adds TODO note to token description
- Flags for manual review
- Requires human decision on split criteria
Rebuilds token path to match semantic ontology.
{
type: "restructure",
targets: ["text.danger.bold"], // Non-standard structure
}Operations:
- Parses token path components
- Rebuilds using ontology rules
- Updates token and references
- Validates new structure
Removes unused token (only if no references exist).
{
type: "delete",
targets: ["legacy.color.old"],
}Operations:
- Checks for references (blocks if found)
- Removes token from map
- Validates no broken dependencies
Creates new semantic token placeholder.
{
type: "create",
targets: ["background.feedback.info"],
}Operations:
- Creates token with placeholder value
- Adds migration description
- Flags for value assignment
The scanner finds token references across multiple file types:
// Import references
import { color } from './tokens';
// Object access
tokens['color.primary']
tokens.color.primary
// Function calls
getToken('color.primary')
useToken('color.primary')
// CSS-in-JS
theme.colors.primary/* CSS variables */
var(--color-primary)
/* SCSS variables */
$color-primary
/* Custom properties */
--color-primary: #007bff;{
"value": "{color.primary}",
"color.primary": "#007bff"
}import { scanTokenReferences } from './lib/migration/scanner.js';
const result = await scanTokenReferences({
rootDir: './src',
tokenPrefix: 'semantic',
include: ['**/*.ts', '**/*.css'],
exclude: ['**/node_modules/**'],
});
console.log(`Found ${result.referencesFound} references in ${result.filesScanned} files`);Post-migration validation ensures system integrity:
- All operations completed successfully
- No duplicate token paths
- No failed actions
- No broken references (all refs resolve)
- No circular dependencies
- All reference chains terminate
- Tokens follow semantic ontology
- Proper structure:
<property>.<context>.<intent>.<state> - Primitives exempted (core., color.)
- No orphaned tokens (unless primitives)
- Reasonable reference depth (<4 levels)
- Proper hierarchy maintained
- Color contrast ratios preserved
- WCAG AA compliance maintained (4.5:1)
- Foreground/background pairs checked
# Migration Validation Report
**Status:** ⚠️ WARNING
## Summary
- ✅ Passed: 4
- ⚠️ Warnings: 1
- ❌ Errors: 0
## Validation Checks
### ✅ Migration Integrity
**Category:** integrity
**Status:** passed
**Details:** Checked 3 phases, found 0 integrity issues
### ⚠️ Accessibility Validation
**Category:** accessibility
**Status:** warning
**Details:** Checked 42 color tokens for contrast
**Issues:**
⚠️ `text.feedback.warning`: Insufficient contrast with background.feedback.warning (ratio: 3.2:1)
- *Suggestion:* Adjust colors to meet WCAG AA (4.5:1 for normal text)Snapshots capture token state before migration:
import { createSnapshot } from './lib/migration/executor.js';
const snapshot = createSnapshot(tokens, {
description: 'Before Phase 1 execution',
phaseNumber: 1,
phaseName: 'Fix Critical Issues',
});
console.log(`Snapshot ID: ${snapshot.id}`);If validation fails or issues arise, rollback to snapshot:
import { rollback } from './lib/migration/executor.js';
rollback(tokens, snapshot);
console.log('Rolled back to previous state');Note: Snapshots are in-memory. For persistent backups, commit to git before migration.
All executions default to dry-run mode. Must explicitly set dryRun: false.
First failure stops execution, preventing cascade issues.
Creates snapshot before execution (can be disabled).
Post-execution validation catches issues before committing.
Execute one phase at a time, validate, then continue.
- Run dry-run on entire scenario
- Execute Phase 1 only (critical fixes)
- Validate thoroughly
- Execute remaining phases if clean
# Before migration
git checkout -b migration/semantic-refactor
git commit -am "Snapshot before migration"
# Execute phase
npm run mcp-tool execute_migration -- \
--scenarioId conservative-001 \
--phaseNumber 1 \
--dryRun false
# If successful
git commit -am "Phase 1: Fix critical issues"
# If failed
git reset --hard HEAD- Validate after each phase
- Check visual regression if available
- Test against component library
- Review accessibility metrics
- Plan: Generate scenarios, review with team
- Preview: Dry-run execution, review changes
- Execute: Phase-by-phase with validation
- Verify: Manual testing of key components
- Document: Update design system docs
Cause: Token marked for deletion still referenced.
Solution:
- Run reference scan to find usages
- Update references or remove from deletion list
- Re-execute
Cause: Token references form a loop.
Solution:
- Check validation report for cycle path
- Break cycle by using direct value
- Re-execute with restructured refs
Cause: Color changes violated WCAG contrast requirements.
Solution:
- Review color pairs in validation report
- Adjust color values to meet 4.5:1 ratio
- Re-execute
Cause: Post-migration checks found issues.
Solution:
- Review validation report details
- Rollback if needed: use snapshot ID
- Fix issues in scenario
- Re-execute
Execute a single migration phase.
async function executePhase(
tokens: Map<string, DesignToken>,
phase: MigrationPhase,
options?: MigrationOptions,
): Promise<PhaseExecution>Scan codebase for token references.
async function scanTokenReferences(
options: ScanOptions,
): Promise<ScanResult>Validate post-migration token system.
async function validateMigration(
tokens: Map<string, DesignToken>,
execution: MigrationExecution,
): Promise<ValidationReport>Create token state snapshot for rollback.
function createSnapshot(
tokens: Map<string, DesignToken>,
metadata: MigrationSnapshot['metadata'],
): MigrationSnapshotRestore tokens to snapshot state.
function rollback(
tokens: Map<string, DesignToken>,
snapshot: MigrationSnapshot,
): void- Phase 5: Codebase integration (build configs, CI/CD)
- Phase 6: Visual regression testing
- Phase 7: Documentation updates
- Phase 8: Team training and handoff
See migration-system.md for scenario generation and risk assessment.