Direct answer
Do not give a Claude Code session production migration authority. Let the agent inspect a read-only schema, propose an expand-and-contract plan, draft migration files and prepare verification. Keep production credentials and the final apply in a separate human-controlled path. Community: issue #27063 reports an agent running drizzle-kit push --force against production (F012). That is a user report, not a confirmed universal bug. It still demonstrates the consequence to design against. The concrete win is a migration draft that can be reviewed without touching production. The honest loss is that tests and dry runs cannot prove rollback safety or data correctness. Pair them with a restore rehearsal, explicit data checks and a named production approver.
Why migrations are different
A code edit can often be reviewed as a diff. A migration changes the system that stores the data the application depends on. The migration file may be small while the operational consequence is large. A dropped column, a rewritten constraint or a long-running backfill can affect behavior beyond the code that triggered it.
A migration also crosses tool boundaries. The agent may inspect schema files, run a generator, execute a command and then verify the result. Official: Claude Code checkpointing tracks its file edits, but Bash-only changes, subagent edits and some external modifications are not fully tracked (F014). A database change made through a shell command is not made safe merely because the session has checkpoints.
The Agent SDK has a similarly bounded model. Official: SDK file checkpointing tracks Write, Edit and NotebookEdit modifications. It excludes Bash commands, subagents and non-regular files such as symlinks. Rewind restores disk content while preserving conversation history (F015). Neither statement supports a claim that rewind restores a database.
Official: dependency installs can run lifecycle scripts and reach the network, and hooks can block tool calls (F011). A migration tool may arrive through a dependency or run as part of a script. Inspect the package and command before granting it database access. The dependency-install safety checklist applies directly.
The practical boundary is simple. The agent can draft a migration without owning production. Separate planning, generation, review and apply so that no single session can silently move through all four stages.
Expand and contract
Expand and contract is a staged schema-change pattern. First add a compatible structure. Then move reads and writes toward it. After the new path is verified, remove the old structure in a later change. The point is to avoid requiring every application instance and every data row to change at the same moment.
Treat this as a proposed workflow, not a claim that one pattern fits every database. Start by describing the current schema, the target schema and the compatibility window. Name the application versions that must coexist during the change. If no coexistence is possible, the plan needs a different deployment strategy and a more explicit outage discussion.
During expansion, add the new column, table or constraint in a form that old code can tolerate. Avoid making the new structure mandatory before the application can populate it. The migration review should explain how existing rows will be handled and when the new path becomes authoritative.
A backfill is the work of populating the new structure for existing data. Explain its expected volume class, locking behavior and restart strategy without inventing a duration. The supplied fact pack contains no benchmark for migration time. Use a staging rehearsal with representative data volume to gather evidence.
During contraction, switch application behavior and verify it. Only then plan removal of the old structure. Removal should be a separate reviewed change with its own backup and restore evidence. Do not let a cleanup request quietly become a destructive production apply.
Official: best practices recommend specific scope, success criteria and independent review (F008, F009). Give a reviewer the migration spec and ask them to focus on correctness and compatibility rather than style. The large-diff scope guide helps keep schema cleanup separate from the functional change.
The session handoff format should carry the migration phase, approved files, data checks and next action. A teammate opening the repository should not have to infer whether the project is still expanding, backfilling or contracting.
Migration phases
| Phase | Agent work | Human decision | Evidence required |
|---|---|---|---|
| Read-only discovery | Inspect schema files and describe current state | Confirm the target and compatibility window | Schema summary and open questions |
| Expansion | Draft additive migration files | Approve the additive structure | Reviewed SQL or migration-tool output |
| Backfill | Draft a bounded data-migration plan | Approve volume, locking and restart approach | Rehearsal record and data checks |
| Application switch | Propose compatible code changes | Approve rollout order | Tests and deployment plan |
| Verification | Prepare read-only checks | Accept or reject the result | Row counts, invariants and application checks |
| Contraction | Draft removal as a separate change | Approve destructive removal | Backup, restore rehearsal and sign-off |
| Production apply | No autonomous apply | Named operator executes the approved command | Apply log and post-apply verification |
The table is a control design. It does not claim that Claude Code enforces these phases automatically. Put the phases in the task contract and enforce the production boundary with credentials, permissions and an independent apply path.
A read-only planning brief
Give the agent a planning task before giving it an execution task. The brief should make the authority limit explicit and ask for uncertainty instead of confident completion.
Inspect only the approved schema files and the redacted fixture. Do not connect to production, run a migration or propose a production apply. Summarize the current structure, the requested behavior and the compatibility window. List every unknown that could change the plan. Draft an expand-and-contract approach with separate expansion, backfill, application switch, verification and contraction artifacts. Identify any destructive statement and keep it in a separate proposal. Return the proposed file paths, the evidence needed for review and the conditions that should stop execution.
The prompt is a template, not a guarantee. The session still needs technical controls around credentials and commands. Its value is that it gives the reviewer a clear expected output and makes “do not apply” part of the task definition. Reject a plan that treats an unknown production condition as settled or bundles a destructive removal into the additive phase without separate evidence.
Ask for the current state in plain language. The agent should name the tables, relationships or constraints it inspected and distinguish schema-file evidence from assumptions. If the repository uses generated schema artifacts, the brief should say which artifact is authoritative and which files are derived.
Require a list of unknowns. Useful unknowns include the volume class of existing rows, the application versions that must coexist, the acceptable lock behavior and the database features available in production. Do not let the agent fill those gaps with invented durations or unsupported guarantees.
The proposed migration should separate additive work from destructive work. If the target requires a removal, ask for the dependency chain and the evidence that would make removal acceptable later. This keeps contraction from being bundled into the first apply merely because the final schema is known.
Finally, require verification ideas before execution. The agent should propose read-only checks for required relationships, expected application behavior and the restored copy. The reviewer can then decide whether the checks are sufficient and add database-specific evidence where needed.
Official: best practices recommend specific scope and independent review (F008, F009). This brief follows that advice by naming the input, the output, the stop conditions and the review evidence. It does not authorize penetration testing, production access or any destructive database command.
Production credentials
Keep production credentials out of the agent session. Use read-only planning access where possible, and run the production apply through a separate operator path with its own authentication and approval record.
A read-only credential still deserves scrutiny. It can expose sensitive schema and data samples. Limit the schema and environment it can reach, and avoid copying production rows into prompts or logs. The secrets-in-logs guide explains why tool output and transcripts need controlled handling.
Do not solve an access error by pasting a production secret into the chat. That turns a permission problem into a data-handling problem. If the agent needs a different schema view, provide a redacted fixture or a controlled staging connection.
Official: settings, permissions and hooks provide controls around tool actions (F011). Use them to block unreviewed migration commands and to keep the agent away from production credentials. The harness security boundary guide distinguishes prompt instructions from configured enforcement.
Production apply should have a named operator and a named approver. The approver reviews the exact migration artifact, the target environment, the backup state and the verification plan. The operator runs the approved artifact without letting the agent rewrite it between approval and execution.
If the artifact changes, approval expires. Even a small edit can change locking, data transformation or destructive behavior. Re-review the new artifact rather than assuming the previous decision still covers it.
Permission matrix
| Role or surface | May inspect | May draft | May execute against staging | May apply to production |
|---|---|---|---|---|
| Agent planning session | Approved schema and fixtures | Plan and migration files | Only if explicitly staged and bounded | No |
| Independent reviewer | Migration artifact and evidence | Review comments | Rehearsal review | Approval only |
| Staging operator | Staging schema | Approved artifact execution | Yes, within the rehearsal plan | No |
| Production approver | Artifact, backup and rehearsal evidence | Approval record | No | Approves, does not silently rewrite |
| Production operator | Target environment | No unreviewed edits | No | Runs the exact approved artifact |
| Emergency path | Incident-specific evidence | Incident-specific plan | Separate controlled process | Separate authorization |
The matrix is proposed practice. It makes the authority boundary visible. A team may combine roles, but the review and apply decisions should remain explicit. Do not rely on the agent to remember an approval that was only discussed in a transcript.
Dry runs
A dry run is a rehearsal against a disposable or staging environment that resembles production closely enough to test the migration’s assumptions. It is not a promise that production will behave identically. Data volume, concurrent traffic, database configuration and extension behavior can change the result.
Start with the exact migration artifact that will be reviewed for production. Do not rehearse one version and apply another. Record the artifact identity, the environment and the command class. If the tool has no safe dry-run mode for the database, say so and design a different rehearsal rather than inventing a flag.
Rehearse the expansion, backfill and application switch in order. Observe whether old and new application versions can coexist. Verify the data invariants that matter to the product, not only whether the schema command returned successfully.
Then rehearse recovery. Restore the backup into a disposable environment and verify that the application can use the restored state. A backup file is not recovery evidence until a restore has been tested. The supplied fact pack does not establish a universal restore time or a guarantee that every database supports point-in-time recovery.
Unknown: Tests and dry runs do not prove rollback safety. They provide evidence about the tested environment and artifact. State what was tested, what data volume was represented and which production conditions remain unknown. Do not convert a successful rehearsal into a blanket safety claim.
Use read-only post-apply checks for row counts, required relationships and application behavior. Define acceptable results before the apply. If a check fails, the operator needs a pre-agreed stop or recovery decision, not an improvised destructive command.
The proof-of-work packet is useful here because it ties each claim to a named check. “Migration passed” is too broad. “The fixture preserved the required relationship and the application test passed against the restored copy” is inspectable evidence.
A migration checklist
Complete the checklist before the production operator receives the artifact. Missing evidence is a reason to pause, not a reason to lower the standard during an incident window.
Checklist
| Check | Pass condition | Evidence |
|---|---|---|
| Target is named | Environment and schema are explicit | Approved task packet |
| Current state is understood | Schema and compatibility assumptions are documented | Read-only discovery summary |
| Phase is clear | Expansion, backfill, switch or contraction is named | Migration plan |
| Artifact is reviewed | Exact file and command class are approved | Review record and artifact identity |
| Destructive actions are separated | Removal or force apply has separate approval | Scoped approval |
| Credentials are separated | Agent has no production apply credential | Access review |
| Dry run is representative | Tested conditions and gaps are stated | Rehearsal record |
| Backup exists | Backup target and completion are confirmed | Backup record |
| Restore is rehearsed | Restored copy passes application checks | Restore evidence |
| Data checks are defined | Invariants and acceptable results are written | Verification plan |
| Stop condition is clear | Operator knows when to halt | Runbook |
| Apply owner is named | One operator owns execution | Apply assignment |
| Post-apply review is assigned | Someone verifies the result | Follow-up owner |
Keep the checklist with the migration artifact. If the team uses a pull request, link the evidence there. If the team uses an incident process, link the controlled record from the task packet. Do not leave the only copy in a mobile approval notification.
Review the final artifact for unexpected destructive statements. A force option, a drop or a broad update deserves explicit discussion. The fact pack does not provide a universal safe-command list, so use the migration tool’s official documentation and the database’s operational guidance.
The gitignored-file deletion guide is a reminder that local recovery and repository state are separate from database recovery. The rewind checkpoint guide explains which file changes may be tracked. Neither is a substitute for a database backup.
A safe migration rehearsal
Use a disposable database with a synthetic schema and synthetic rows. Do not connect production credentials and do not run destructive commands against a real database for the demonstration.
Write the current schema, target schema and compatibility requirement first. Ask the agent for a read-only assessment and a proposed migration artifact. Keep production apply out of scope. Review the artifact before any staging execution.
Create a backup of the disposable database and restore it into a second disposable environment. Run the migration against the first copy. Verify the schema, data invariants and application behavior. Then test the recovery path on the restored copy. Record which steps succeeded and which assumptions were not tested.
Derived: A migration readiness gate is ready = artifact reviewed + environment named + credentials separated + dry run recorded + backup confirmed + restore rehearsed + verification defined + apply owner named. Every term must be true. This is a process gate, not a probability of success.
The safe rehearsal has a concrete win: it exposes mismatches between the plan, the artifact and the application before production. Its concrete loss is that synthetic data may not represent production volume or concurrency. The practical implication is to state those gaps and obtain additional evidence when the change is high consequence.
Official: independent review is recommended because a fresh reviewer has not seen the implementation reasoning (F009). Apply that advice to the migration artifact and the operational plan. A reviewer who only reads the agent’s explanation may inherit its blind spots.
Honest loss and data gaps
A controlled workflow cannot eliminate migration risk. It can make authority, evidence and uncertainty visible. The supplied sources do not provide a universal rollback guarantee, a safe migration duration or a measured incident rate for Claude Code database changes.
Community: issue #27063 is a report of a forced production push (F012). It does not prove that every agent will choose that command or that Anthropic confirmed a universal defect. Use it as a failure case for separation of duties, not as a benchmark.
Official: checkpointing covers file edits with documented exclusions, and SDK checkpointing excludes Bash commands and subagents (F014, F015). Do not tell a team that /rewind restores a dropped table or an applied migration. Database recovery needs its own backup and restore evidence.
Unknown: The fact pack does not establish that tests prove rollback safety, that every dry run predicts production behavior or that one expand-and-contract pattern fits every database. Those claims would exceed the evidence. Record the tested conditions and revisit the plan when the schema, data volume or deployment model changes.
The honest loss is operational effort. A separate apply path, restore rehearsal and independent review take time. The practical implication is to spend that effort where data loss or downtime would be costly, while keeping low-risk additive work proportionate and reviewable.
Adjacent checks worth keeping separate
Migration safety starts with team handoff and approvals, offline work boundaries, mobile approval limits and large-diff scope control. The migration tool may arrive through dependency-install side effects. Platform faults belong with network storm diagnosis, Linux ARM and headless login, macOS Keychain permissions, PowerShell path quoting, corporate proxy TLS and mTLS and outage failover.
Recovery claims must match the changed surface. Review gitignored-file deletion and rewind checkpoint limits, but keep database restore evidence separate. A file checkpoint does not restore external state.
Untrusted context can influence a migration plan. Use repository prompt-injection controls, MCP trust boundaries, plugin security audits, secrets-in-logs cleanup, security-research authorization and game-development IP restrictions. A migration tool result is evidence to inspect, not an instruction to broaden production authority.
Cost and reasoning choices do not authorize a destructive apply. Compare annual plan lock-in, Max and Ultra value, fast-mode pricing and Batch API versus subscription. Tune requests with prompt-cache minimums, thinking-token caps and reasoning effort defaults. Keep review capacity, AI provenance and license compliance attached to the migration and its generated code.
A practical OpenAI-format alternative
If you want to compare migration-plan drafting in an OpenAI-format agent, the 46 live free model IDs provide a separate connected route. First-party, checked 2026-11-27: the catalogue showed 76 listed models and 46 available-now free IDs across 22 families (F044). The free lane shares 100 requests and 5,000,000 tokens per day per account, resetting at 05:30 IST or 00:00 UTC, with one request in flight per key (F045).
One AI API Key works through OpenAI-format agents such as OpenCode, Cline or Cursor. Follow the endpoint quickstart, select one free ID and use https://api.oneaiapikey.com/v1 (F047, F048). The prepaid pricing page documents $10 signup credit with no card and no subscription or seat fee (F046). Use per-key caps, expiry and model allowlists, and the cost calculator, for a small controlled comparison.
Do not put these free IDs into Claude Code. They are OpenAI-format only. The documented Claude Code route is unavailable because all four Claude IDs were marked unavailable on 2026-11-27 (F047). A second model does not change the production boundary. Keep credentials, approval and apply under separate human control regardless of which agent drafts the migration.
FAQ
Can Claude Code generate a database migration?
It can draft migration artifacts and a plan within the task boundary. The supplied evidence does not establish a universal migration generator or a safety guarantee. Review the exact artifact and keep production apply separate.
Does /rewind undo an applied migration?
No. Official: checkpointing has exclusions, and SDK file checkpointing excludes Bash commands and subagents (F014, F015). Database recovery requires its own backup and restore process.
Is a successful dry run enough for production?
No. It provides evidence about the tested environment and artifact. State the gaps in data volume, concurrency and configuration, and rehearse recovery separately.
Why separate production credentials?
Separation prevents an agent session from silently moving from drafting to applying. A read-only planning path can still expose sensitive schema, so scope and redact it carefully.
What is expand and contract?
It is a staged pattern: add a compatible structure, move application behavior, verify the new path and remove the old structure later. It is a proposed workflow here, not a universal fit for every database.