
# Mirror DB tools

Your mirror's database is yours to break. `agc db` opens `psql`, `agc db query` runs one SQL string and returns JSON, `agc db diff` shows what the last `agc migrate` changed, and `agc db reset` replaces the mirror with a fresh one. All need a mirror (`agc up --detach`).

```bash runnable
agc up --detach
agc db query "SELECT count(*) FROM pg_tables WHERE schemaname = 'public'"
agc migration new try_diff
agc migrate
agc db diff
```

## Ask your agent

```text
Apply my new migration to the mirror and summarize what it changed in the schema and how many rows changed per table. Don't paste any rows.
```

```text
Add Agent Cloud seed data: one demo person and three sample bookings, so the mirror has something to look at. Use made-up details only.
```

## Steps

### `agc db`: psql on the mirror

```bash
agc db
```

Interactive, for a person at a terminal: it runs `psql` with the mirror's credentials. Without a terminal it refuses with `db.needs_terminal`. Any other client can use the `database.host` and `database.port` that `agc up` prints. The password is injected by `agc db` and `agc exec`, never printed.

### `agc db query`: one SQL string, JSON back

```bash
agc db query "UPDATE camps SET capacity = 1 WHERE id = 7 RETURNING id"
```

Runs on the mirror with full rights: reads, writes and DDL. Several statements separated by `;` are allowed, and the answer describes the last one. `rows` holds at most 100 rows, `row_count` the real count, `truncated` whether it was cut. Add `--env prod` to read the masked branch of production instead ([Reading production safely](/docs/data/reading-production-safely.md)).

Long SQL can come from a file or standard input instead, up to 5 MB; `data.source` names the file, never the SQL:

```bash
agc db query --file fix-camps.sql
agc db query - < fix-camps.sql
```

```json
{
  "ok": true,
  "product": "agent.cloud",
  "command": "db query",
  "data": { "env": "mirror", "mirror": "main", "command": "UPDATE", "row_count": 1, "rows": [{ "id": 7 }], "truncated": false },
  "next": []
}
```

Schema changes made this way stay on your mirror; production's go in a migration file.

### `agc db diff`: what the migrations did

```bash
agc db diff
```

Compares the mirror now with the snapshot `agc migrate` took just before it last applied migrations:

```json
{
  "ok": true,
  "product": "agent.cloud",
  "command": "db diff",
  "data": {
    "mirror": "main",
    "compared": "mirror now vs. just before the last `agc migrate`",
    "schema": {
      "tables_added": [],
      "tables_removed": [],
      "columns_added": ["requests.amount_cents"],
      "columns_removed": [],
      "types_changed": []
    },
    "tables": [
      { "table": "requests", "rows_before": 1200, "rows_after": 1200, "inserted": 0, "deleted": 0, "updated": 1200, "unchanged": 0, "capped": false }
    ]
  },
  "next": [{ "cmd": "agc db query \"<SELECT …>\"", "why": "look closer at a table that changed" }]
}
```

Row changes are found by hashing each row under its key: `inserted`, `deleted`, `updated`, `unchanged`. A table over 200,000 rows is compared on its first 200,000 and marked `capped: true`. Because it compares with "now", writes your app made since the migration show up too.

### `agc db reset`: start over

```bash
agc db reset
```

Deletes the mirror (`agc down --delete`) and runs `agc up`. You get a fresh masked branch of today's production, or, for an app with no data yet (and on a customer's private target), a schema with migrations and seed applied again. Use it after `migrate.modified_after_apply`, a failed `no-transaction` migration, or a seed command that half-ran. Anything you wrote on the mirror is gone.

## Seed data

A seed is a few made-up rows for a mirror that starts with no data: a new app nobody has used yet, and every mirror of an app on a customer's private target. `agc up` applies the migrations, runs the seed once, then starts the app, and its envelope shows `"seeded": { "source": "seed.sql" }`. Agent Cloud never runs a seed in production or a rehearsal.

```toml
[data.db]
seed = "seed.sql"
```

Write inserts that are safe to run twice, using only tables your migrations create:

```sql
INSERT INTO users (id, email, name)
VALUES ('6f1c2b4e-0d6a-4f38-9b1e-2a7c5d9e8f01', 'demo@example.test', 'Demo Person')
ON CONFLICT DO NOTHING;
```

```bash runnable
agc up --detach
agc status
```

**When a mirror starts empty.** Agent Cloud decides when it creates the mirror. A branch whose tables hold no rows, other than Agent Cloud's own `agentcloud_*` tables, is empty. A copy from the past (`agc up --at`) never is. On a customer's private target every mirror is a schema-only branch with production's migration ledger copied in, so it's always empty.

**Order on `agc up`.** For an empty mirror, agc first records that it started empty, then applies the migrations exactly as `agc migrate` would, runs the seed, and only then starts the app. A mirror made from production data gets neither, so you run `agc migrate` yourself.

**Once per mirror.** The mirror's own database records in `agentcloud_seed` that it started empty and whether the seed ran. The record survives `agc down` and a new laptop, and a seed never runs twice on one mirror. A mirror that started empty without a seed applied gets it from the next `agc up` or `agc migrate` once its migrations are up to date. That's how a seed you add or fix later reaches it without a reset: run `agc migrate`. `agc db reset` makes an empty app's mirror migrated and seeded again.

| Form | How it runs | On failure |
|---|---|---|
| `seed = "seed.sql"` | The file, relative to the app root, in one transaction with the seed's mark | Rolled back: the mirror holds the schema and nothing half-seeded |
| `seed = { command = "npm run seed" }` | In the app root with the mirror's environment (its `DATABASE_URL`, `AGENTCLOUD_MIRROR`), inside the mirror's sandbox, like `dev` | Not transactional; the last lines of output come back in `data.log_tail` |

Prefer the SQL file: it's atomic. Use a command only when app code must build the rows.

**Who may depend on it.** `agc verify` goals may ("sign in as the demo person and see three bookings"). Checks must not: rehearsals run on a branch of production, which never had the seed, and `agc check` doesn't run it. If the seed fails, `agc up` doesn't start the app:

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "up",
  "data": { "mirror": "main", "migrated": ["20261001120000_init"] },
  "error": {
    "code": "seed.failed",
    "message": "seed.sql failed: relation \"bookings\" does not exist",
    "fix": "Fix seed.sql; it was rolled back, so the mirror holds the schema and nothing half-seeded. Then `agc migrate` runs it again.",
    "retryable": false,
    "docs": "agc help mirror"
  },
  "next": [
    { "cmd": "agc migrate", "why": "run the fixed seed; migrations are already applied" },
    { "cmd": "agc db reset", "why": "a clean mirror, migrated and seeded again" }
  ]
}
```

## Reference

| Command | Where it runs | Needs |
|---|---|---|
| `agc db [name]` | Mirror | A terminal and `psql` |
| `agc db query "<sql>" \| --file <path> \| - [--env prod] [--fresh] [--name <mirror>]` | Mirror, or masked production with `--env prod` | A running mirror (not for `--env prod`) |
| `agc db diff [name]` | Mirror | A previous `agc migrate` |
| `agc db reset [name]` | Mirror | Nothing; makes a new one |

`name` picks a mirror other than the one for the current git branch.

| Seed item | Value |
|---|---|
| Key | `[data.db] seed`: a string (file) or `{ command = "…" }` |
| Mark table | `agentcloud_seed`, in the mirror's database |
| `agc up` data | `migrated` (stems applied), `seeded.source` |
| `agc status` | A mirror's `seed` is `"done"` or `"failed"` |

## Errors

| `code` | Exit | Cause | Fix |
|---|---|---|---|
| `db.needs_terminal` | 2 | `agc db` without a TTY | Use `agc db query` |
| `db.no_psql` | 1 | `psql` isn't installed | Install the PostgreSQL client, or use `agc db query` |
| `query.empty` | 2 | No SQL | Pass a statement in quotes |
| `db.bad_request` | 2 | SQL given two ways, or a `--file` it can't read | Give the SQL one way |
| `db.query_too_large` | 2 | The file or standard input is over 5 MB; nothing ran | Split it into files under 5 MB |
| `query.failed` | 1 | Postgres rejected the SQL on the mirror; `message` is its error | Fix the SQL |
| `diff.no_snapshot` | 1 | No migration has run on this mirror | Run `agc migrate` |
| `mirror.not_running` | 1 | No mirror for this folder | `agc up --detach` |
| `seed.missing` | 2 | The manifest names a seed file that doesn't exist; checked before anything is forked | Add the file, or remove `seed` |
| `seed.failed` | 1 | The seed SQL errored (rolled back), or the command exited non-zero, or couldn't run in the sandbox | Fix it, then `agc migrate`; after a failed command, `agc db reset` for a clean mirror |

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "db",
  "error": {
    "code": "db.needs_terminal",
    "message": "`agc db` opens an interactive SQL shell, which needs a terminal.",
    "fix": "From an agent, run `agc db query \"<sql>\"` instead.",
    "retryable": false,
    "docs": "agc help data"
  },
  "next": [{ "cmd": "agc db query \"SELECT …\"", "why": "run one statement and get JSON back" }]
}
```

## Agent notes

- `agc db diff` output contains no row values, but `agc db query` does. Summarize; don't paste rows into chat, logs or commits.
- `agc db reset` throws away rows you made for testing; smoke flows should create their own.
- Seed data is made up: `example.test` emails, fixed uuids. Never copy rows from production or the mirror into it, and write it with `ON CONFLICT DO NOTHING` so a retried command doesn't fail on duplicates.

## Related

- [Migrations](/docs/data/migrations.md)
- [Reading production safely](/docs/data/reading-production-safely.md)
- [Local development with agc up](/docs/build/local-development-with-agc-up.md)
- [Data on private targets](/docs/data/reading-production-safely.md#data-on-private-targets)
- [AI browser verification](/docs/checks/ai-browser-verification.md)

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