
# Migrations

Production's schema and data change only through SQL files in `migrations/`. `agc migrate` applies new files to your mirror, and `agc ship` applies them to production after rehearsing them on a branch of production. Success on the mirror is the stem in `data.applied`; in production, exit 0 with `"outcome": "live"`.

## Execution contract

- **Before starting:** A linked app, a running mirror, and (for the example) a `bookings` table.
- **Do:** `agc migration new <slug>`, write SQL, then `agc migrate`, `agc db diff`, `agc check`, `agc ship`.
- **Success:** The stem in `data.applied`; in production, exit 0 and `"outcome": "live"`.
- **If blocked:** Never edit an applied file; fix with a new migration. A failed check blocks the ship.
- **Human handoff:** Every ship containing migrations requires a person; relay the decision and wait.

## Ask your agent

```text
Add a "phone" column to bookings. Write it as an Agent Cloud migration, apply it to the mirror, run the checks, then ship it.
```

You'll get an approval question in chat, or a console link when the change drops or empties data.

## Steps

```bash
agc migration new add_booking_phone
```

That writes `migrations/<timestamp>_add_booking_phone.sql` and prints its stem:

```json
{
  "ok": true,
  "product": "agent.cloud",
  "command": "migration new",
  "data": {
    "stem": "20261020150211_add_booking_phone",
    "path": "/Users/you/camp-bookings/migrations/20261020150211_add_booking_phone.sql"
  },
  "next": [
    { "cmd": "agc migrate", "why": "apply it to your mirror once written" },
    { "cmd": "after = \"20261020150211_add_booking_phone\"", "why": "reference this stem from invariants on the columns it adds" }
  ]
}
```

Add the SQL under the two comment lines agc put in the file:

```sql
ALTER TABLE bookings ADD COLUMN phone text;
```

Apply it to the mirror and run the checks. `agc check` also applies anything pending first (never the seed) and lists those stems in `data.migrated`, so a migration it can't apply or prove fails the check the way it fails `agc migrate`.

```bash
agc up --detach
agc migrate
agc db diff
agc check
```

Then ship. It waits for a person (exit 10) before anything reaches production:

```bash
agc ship
```

## How it works

**Naming.** A migration is `<digits>_<slug>.sql`, or a folder `<digits>_<slug>/migration.sql`, with a slug of lower-case letters, digits, `_` and `-`. Files run in numeric order of the prefix, then name, so `001_init` and `20261001120000_amount_cents` can live together. Anything else in the folder is ignored. The stem, the name without `.sql`, is what invariants' `after` and `until` refer to.

**The ledger.** Agent Cloud records each applied file, with its sha256, in `agentcloud_migrations (name text PRIMARY KEY, checksum text, applied_at timestamptz)` in the same database, on the mirror and in production. A file named there never runs again, and one whose checksum changed is refused: `migrate.modified_after_apply` on the mirror, `ship.migration_modified` at ship. Fix a mistake with a new migration.

**One transaction per file.** Each file runs inside `BEGIN … COMMIT` with its ledger row, so a failure leaves nothing behind and nothing after it runs. `$$` function bodies, triggers and `DO` blocks all work. A file whose first nonblank line is `-- agentcloud: no-transaction` (case-insensitive) runs without the wrapper, which `CREATE INDEX CONCURRENTLY` needs.

| `agc migrate` on a mirror | |
|---|---|
| 1 | Compares the files with the mirror's ledger |
| 2 | Snapshots the mirror (the "before" for `agc db diff`) |
| 3 | From a separate session, fingerprints each `hold = "unchanged"` or `equal:` invariant and sets aside every table's primary keys |
| 4 | Applies each pending file and its ledger row |
| 5 | Proves nothing was lost: every existing row is still found by its key, and `unchanged` checks return the same result. A table or column that held data may disappear only if the header declares it (`-- agentcloud: drops bookings.notes`). Otherwise `migrate.not_preserved` (exit 11); see [Safe schema changes](/docs/data/safe-schema-changes.md). Rows it can't compare by key are reported as `rows not proven preserved`, not failed |
| 6 | Runs the seed if the mirror started empty and hasn't been seeded ([Seed data](/docs/data/mirror-db-tools.md#seed-data)) |

| `agc ship` | |
|---|---|
| Pending | The CLI sends every file; those missing from production's ledger are pending |
| Rehearsal | Applies them to a fresh branch of production and runs the same proof as step 5, reporting only pass or fail |
| Decision | Any pending migration makes the release a person's decision ("Changes the production database"). `DROP`, `TRUNCATE`, `DELETE`, an `UPDATE` without `WHERE`, `ALTER … TYPE`, a `DO` block or `EXECUTE` (including `CREATE TRIGGER … EXECUTE FUNCTION`) is decided in the console only, never in chat, and so is a release whose rehearsal couldn't prove some rows preserved |
| Promotion | Once approved, the migrations run on production first, and only then does traffic move. The old release serves on the new schema until the switch, so changes must be backward compatible. If one fails here, earlier files in the same ship stay applied; fix forward with a new migration |

**Never the app's own migrator.** If the repo has Prisma, Drizzle, Alembic, Rails or a hand-written migrator, don't run it on the mirror or call it from `start`. DDL from anything but a migration file skips the rehearsal and the person's approval. `agc init` notes a `schema_migrations` ledger when it finds one. A `[data.db]` with `tool = "command"` is refused with `cli.not_available`: convert each of the app's migrations to a `<digits>_<slug>.sql` file, then remove `tool`, `apply` and `ledger`, or set `tool = "sql"`.

## Testing against production data

Test a migration twice: on the masked mirror while you write it, and on an exact copy right before it ships. For values it must not change, add invariants. `hold = "unchanged"` runs a query before and after the migrations (around `agc migrate`, and again in the rehearsal) and requires the same result. `hold = "equal:<check>"` requires a new query, after them, to return what a named check returned before. Together they prove a backfill:

```toml
[[check.invariant]]
name = "booking totals in dollars"
sql  = "SELECT status, sum(amount) FROM bookings GROUP BY 1"
hold = "unchanged"

[[check.invariant]]
name = "totals survive the move to cents"
sql  = "SELECT status, sum(amount_cents) / 100.0 FROM bookings GROUP BY 1"
hold = "equal:booking totals in dollars"
```

| Stage | Data | What it proves | What you see |
|---|---|---|---|
| `agc migrate` + `agc check` | Masked branch of production | The SQL runs; rows survive; invariants hold on production-shaped data | Full detail: `agc check` reports what the last `agc migrate` proved, with rows |
| Rehearsal in `agc ship` | Fresh unmasked fork, made seconds before | The same on real values masking would have changed (lengths, uniqueness), plus the new code's smoke flows, so a migration that breaks the app's queries fails here | Check names and pass or fail. A failed check (including `no existing row was deleted`) exits 11 with `ship.check_failed`; a migration error exits 1 with `ship.migration_failed`. Production is unchanged either way |
| Promotion | Production | Runs only after the rehearsal passes and a person approves; one that deletes data waits in the console | `"outcome": "live"` |

## Reference

| Item | Value |
|---|---|
| Folder | `[data.db] migrations`, default `migrations/` ([manifest reference](/docs/reference/agentcloud-toml-reference.md)) |
| Declared removals | `-- agentcloud: drops …` and `-- agentcloud: rekeys …` ([header directives](/docs/data/safe-schema-changes.md#migration-header-directives)) |
| `agc migrate` success data | `mirror`, `applied` (stems), `preserved` (the proof results), `snapshot_taken_at`, `timings.snapshot_s`, `timings.total_s`, and `seeded.source` when a seed ran, and `warnings` naming each table without a primary key. With nothing pending: `up_to_date: true`, plus `applied_but_missing_files` if the ledger names files that are gone |

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md). A failing example:

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "migrate",
  "data": { "mirror": "main", "applied": [], "failed": "20261020150211_add_booking_phone" },
  "error": {
    "code": "migrate.failed",
    "message": "20261020150211_add_booking_phone failed: column \"phone\" of relation \"bookings\" already exists",
    "fix": "Fix 20261020150211_add_booking_phone; it was rolled back, and nothing after it ran.",
    "retryable": false,
    "docs": "agc help migrations"
  },
  "next": [{ "cmd": "agc migrate", "why": "rerun after fixing the file" }]
}
```

## Limits

| What | Value |
|---|---|
| Invariant statement timeout | 30 s for plain invariants; 60 s for `unchanged` and `equal:` queries |
| Largest table the row check compares | 5,000,000 rows |

## Agent notes

- `agc migration new` writes `-- <stem>` as the first line. To opt out of the transaction, replace that line with `-- agentcloud: no-transaction`; below another comment it isn't detected. A `no-transaction` file with several statements still runs as one implicit transaction, so `CREATE INDEX CONCURRENTLY` must be alone in its file.
- Masking can hide failures that depend on real values, such as a unique index over emails, so a passing `agc check` doesn't replace the rehearsal.
- Keep rows and credentials from `agc db diff` out of chat and commits, and row contents out of migration-time logs: the rehearsal's own log isn't masked.

## Related

- [Safe schema changes](/docs/data/safe-schema-changes.md)
- [Invariants](/docs/checks/invariants.md)
- [Rehearsals](/docs/concepts/rehearsals.md)
- [Mirror DB tools](/docs/data/mirror-db-tools.md)
- [Importing existing data](/docs/data/importing-existing-data.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "data/migrations: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
