Create a repeatable code-migration workflow with rollback safety
Some migrations happen once. Others happen dozens of times — every service on the team needs the same treatment. Build a workflow that handles both cases safely: reproducible, verifiable, with rollback baked in.
Prerequisites
- A migration that will happen more than once (across services, packages, or files)
- Familiar with safe refactoring patterns
- Comfortable with subagents and orchestration
- A test suite reliable enough to trust for verification
What you'll learn
- How to distinguish "one-off migration" from "repeatable migration"
- How to encode the migration as a reproducible workflow
- How to build rollback into the workflow (not as an afterthought)
- How to verify each migration completed correctly
- When to stop the workflow because something's wrong
Some migrations are surgical — one-time work with unique context. Others are mechanical — the same treatment applied to every service, every package, every file. The mechanical ones benefit from a workflow. Not because the work is boring (though it often is), but because the same treatment applied inconsistently produces inconsistent results.
This tutorial builds a repeatable migration workflow. The specific example: migrating a monorepo's packages from an old logging library to a new one. Every package needs the same treatment: swap import, adjust log calls, verify tests still pass. Doing this 40 times manually is a slog and error-prone. Doing it via a workflow is faster, more consistent, and reversible if something breaks.
The workflow only helps if the migration is genuinely mechanical. If each package needs judgment about how to migrate, a workflow will produce mediocre results across the board.
Signs a migration is workflow-appropriate:
- Same shape of change across every target (add this import, change these calls, remove these deprecated calls)
- Verification is mechanical (tests pass, types compile)
- Rollback is straightforward (revert the specific changes)
- Order between targets doesn't matter (or has clear dependency graph)
Signs it's NOT workflow-appropriate:
- Each target needs a different approach
- Verification requires human judgment ("does this feel right?")
- Some targets have unusual patterns the migration doesn't cover
- The right approach depends on business context ("we can't migrate that service until Q4")
Can you describe the migration in specific rules? "Every import of old-logger becomes new-logger. Every logger.warn() call becomes logger.warning(). Every logger.setLevel() call is removed." If you can't articulate the rules that specifically, the migration isn't ready for automation.
# Migration: old-logger → new-logger
## Import replacements
- `import { Logger } from 'old-logger'`
→ `import { Logger } from 'new-logger'`
- `import * as OL from 'old-logger'`
→ `import * as NL from 'new-logger'` and update all references
## Method renames
- `logger.warn(msg)` → `logger.warning(msg)`
- `logger.setLevel(level)` → remove entirely (new-logger uses env var)
## Signature changes
- `logger.log(level, msg)` old signature
→ `logger.log({ level, message: msg })` new signature
- Metadata is now the second arg, not spread:
`logger.info(msg, key, val)` → `logger.info(msg, { key: val })`
## Configuration
- `logger.configure({ ... })` calls should be removed
- Configuration now happens via environment variables
## Files to skip
- Test files with mock loggers (leave the mock alone)
- Files under `legacy/` directory (out of scope)
- Files that already import from new-logger (already migrated)
## Success verification
- Package tests pass: `pnpm test`
- TypeScript compiles: `pnpm tsc --noEmit`
- No remaining references to old-logger:
`grep -r "old-logger" src/` returns nothing
The rules doc is the source of truth. Everything downstream (subagent prompts, verification checks, rollback logic) refers back to this. When you find an edge case in a real migration, update the rules doc first, then update the workflow.
---
description: Migrate a single package from old-logger to new-logger
model: claude-sonnet-4-6
allowed-tools:
- Read
- Write
- Edit
- Grep
- Bash(pnpm:*)
- Bash(git:*)
---
# Logger Migrator
You migrate one package from old-logger to new-logger following the
rules in `migration-rules.md`.
## Process
1. Read `migration-rules.md` for the exact rules
2. Read `package.json` to confirm this package uses old-logger
3. Grep for all uses of old-logger in this package
4. Apply the rules to each file:
- Update imports
- Rename methods (warn → warning)
- Update signatures (log, info metadata)
- Remove logger.setLevel and logger.configure calls
5. Update package.json:
- Remove old-logger dependency
- Add new-logger dependency (version from migration-rules.md)
6. Run verification:
- `pnpm install`
- `pnpm tsc --noEmit`
- `pnpm test`
7. If verification fails: STOP. Report the failure. Do not commit.
8. If verification passes: create a commit with a clear message
## What to do when the rules don't cover a case
Do NOT invent a treatment. Instead:
1. Note the case (file, line, code)
2. Stop the migration for this package
3. Report to the user with the specific case
4. Ask the user to update migration-rules.md, then re-run
## Rollback
If verification fails partway through:
1. Note where in the migration you stopped
2. `git checkout -- .` to discard all changes
3. Report to user with the exact failure
Do NOT try to partially apply or fix the migration mid-flight.
The subagent has explicit stop conditions. This is essential — a workflow that continues past unclear cases produces bad output at scale. Stop early, report, let humans decide.
---
description: Migrate all packages from old-logger to new-logger
allowed-tools:
- Read
- Bash(pnpm:*)
- Bash(git:*)
---
# /migrate-logger-all
Migrate every package in the monorepo from old-logger to new-logger,
one at a time, with verification and rollback per package.
## Process
1. Discover packages that use old-logger:
`pnpm ls --recursive --depth 0 old-logger --json`
2. For each package (in dependency order):
a. Note the package name and path
b. Create a branch: `logger-migration-{package-name}`
c. Invoke @logger-migrator with the package path
d. If migrator reports success:
- Verify one more time (pnpm test at monorepo level)
- Open a PR (per package, small and reviewable)
- Note "migrated" in `.claude/logger-migration-status.md`
e. If migrator reports failure:
- Delete the branch
- Note "failed: [reason]" in status file
- Continue to next package
3. Produce final report:
- Packages migrated successfully: N
- Packages that failed: M (with reasons)
- Packages skipped: X (with reasons)
- PRs opened: [links]
## Human involvement
- Human reviews each PR before merging
- Merge order matters for dependency graph — merge leaf packages first
- Status file tracks progress across sessions
The orchestrator does NOT auto-merge PRs. Each migration produces a PR for human review. This is the safety net — even if the subagent produces subtle bad output, human review catches it before it lands.
Trust nothing without verification. After each package migration, verify:
- Package tests pass — the direct check
- TypeScript compiles — catches type errors the migration introduced
- No lingering old-logger references — grep for the old import
- New-logger is actually used — the migration didn't just delete without replacing
- Monorepo-wide tests pass — the migration didn't break packages that depend on this one
The last check catches the sneaky failure mode: your package tests pass in isolation but a downstream package that uses your API breaks. Only monorepo-wide verification catches this.
Verification takes time — running the full monorepo test suite after every package migration might mean the workflow runs for hours. Trade-off: for critical migrations, do it. For lower-risk ones, batch verification (verify after every 5 packages). Never skip entirely.
Even with clear rules, some packages will surprise you. Old code paths, unusual patterns, legacy compatibility. Your workflow needs to handle these gracefully — not produce bad migrations, and not silently skip.
The pattern that works:
- Subagent stops when it hits an unclear case
- Orchestrator notes "failed: [reason]" in status file
- Workflow continues with other packages
- At the end, humans review the failure list
- For each failure: update rules and retry, do manually, or skip entirely (documented)
This means the workflow might migrate 30 of 40 packages automatically, with 10 needing human attention. That's still a massive improvement over doing all 40 manually — and the 10 that need human attention are exactly the ones where automation would have been dangerous.
Before running the workflow across all 40 packages, run it on 2-3 and inspect the results carefully.
- Are the PRs the right shape? Not too big, not missing changes
- Do the tests really pass? Or does it produce false confidence?
- Is the migration actually correct? Human review catches subtle problems
- Are the failure cases handled gracefully? Try to trigger one deliberately
If the small subset works well, scale up. If it doesn't, iterate on the rules and subagent before running against everything. Fast iteration on a small subset is much better than fixing 40 broken PRs after the fact.
Even without running the full workflow, sketch out what "the same treatment across many things" looks like for a migration your team has coming up. Would this workflow shape help? What are the edge cases? Just thinking through it usually clarifies whether automation is worth building.
Recap
You built a repeatable code-migration workflow — explicit rules, a per-target subagent, an orchestrator that handles the whole set, verification between steps, and safe handling of edge cases.
The design principles: explicit stop conditions, per-target verification, PR-per-package for human review, graceful degradation when edge cases appear. Automation for the mechanical part; humans for the judgment.
This same pattern generalizes to any migration that touches many targets: framework upgrades, dependency migrations, API version transitions, schema evolution. What varies is the rules; what stays the same is the discipline of automate-carefully with humans-in-the-loop.
Common gotchas
- Workflow migrates a package that shouldn't have been migrated: Rules were too broad. Add an explicit skip list (files or packages that should never be touched). Or add stricter matching conditions in the rules.
- Verification passes but downstream packages break: Package-level tests miss cross-package regressions. Add monorepo-wide verification after each migration, or at intervals. This is expensive but essential for changes that affect public APIs.
- PR queue overflows during migration: Expected. Warn the team ahead: "I'm running a logger migration, expect ~40 small PRs over the next week." Get reviewer capacity ahead of time. Or batch PRs by owner (group all payments-team packages).
- Some migration attempts corrupt the git state: Subagent should always work in a clean branch and reset on failure. If it leaves the tree in a bad state, that's a bug in the subagent. Fix by adding explicit git status checks between operations.
- Team stops trusting the automation after one bad migration: Expected reaction. Don't fight it. Slow down, address the specific failure, share the learnings. Trust rebuilds through demonstrated reliability, not through arguing about it.
Get cctk to skip the boilerplate
Everything in this tutorial is already scaffolded in cctk — commands, subagents, hooks, MCP configs. Install and customize instead of starting from scratch.