# Add an Audit Log to a Prisma Project

Yes. An agent adds an AuditLog model and migration, records every create, update and delete through a Prisma Client extension, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-audit-log/prisma/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the schema and the code that writes through it. In a project laid out like trpc/examples-next-prisma-starter, `prisma/schema.prisma` has a `postgres` datasource read from `DATABASE_URL` and one model, `Post`, with a UUID `id`, `title`, `text`, `createdAt` and an `updatedAt` marked `@updatedAt`; `prisma/migrations/` holds four migrations starting at `20211019164222_init`, and `prisma/seed.ts` upserts one post by a fixed id. `src/server/prisma.ts` creates a single `PrismaClient` on `globalThis` with query logging in development, `src/server/routers/post.ts` is the only writer, with `add` calling `prisma.post.create` behind a `defaultPostSelect`, and `src/server/routers/post.test.ts` is a Vitest integration test that adds a post through `createCaller` and reads it back. `package.json` runs `prisma migrate deploy` in `prebuild` and `prisma migrate dev` in `migrate-dev`, and `.github/workflows/main.yml` starts a Postgres service for both the unit and the end-to-end jobs.

The log is a new model in `schema.prisma`: `AuditLog` with an `id`, the `model` and `recordId` it refers to, an `action` (`create`, `update`, `delete`), a `before` and `after` column of type `Json?`, an optional `actor`, and a `createdAt` default of `now()`, with an index on `(model, recordId)` and one on `createdAt`. The agent writes it as a migration with `prisma migrate dev --name audit_log`, so a new SQL file appears under `prisma/migrations/` next to the four existing ones and `migration_lock.toml` stays on `postgresql`; it is a pure addition, so `prisma migrate deploy` in `prebuild` applies it on the next build with no data to move.

The recording happens in one place, `src/server/prisma.ts`, with a Prisma Client extension. The extension's `query.$allModels` hook wraps `create`, `update`, `upsert` and `delete`: for an update or delete it reads the current row inside the same `$transaction`, runs the operation, then writes an `AuditLog` row with the before and after values, skipping the `AuditLog` model itself so the log never logs its own writes. `createMany`, `updateMany` and `deleteMany` are logged as a single row with the filter, because Prisma does not return the affected rows for them, and the pull request says so. The exported `prisma` keeps its type, so `post.ts` and `defaultPostSelect` do not change, and the `globalThis` cache still holds one client in development.

The test extends `src/server/routers/post.test.ts`: after `caller.post.add`, it reads `prisma.auditLog.findMany` for that post's id and expects one `create` row whose `after.title` matches the input, then updates the row directly through the client and expects an `update` row with both `before` and `after`. The agent runs `pnpm prebuild` to apply the migration against the Postgres the workflow provides, `pnpm test-unit`, `pnpm tsc` and `pnpm lint` the way `main.yml` does, and opens the pull request when all four pass.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add an audit log to this Prisma project. Read prisma/schema.prisma, prisma/migrations/, prisma/seed.ts, src/server/prisma.ts, src/server/routers/post.ts, src/server/routers/post.test.ts, package.json and .github/workflows/main.yml first. Add an AuditLog model with id, model, recordId, action, before and after as Json?, an optional actor and createdAt, with an index on (model, recordId) and one on createdAt, and create its migration with prisma migrate dev --name audit_log. In src/server/prisma.ts, extend the client with a query.$allModels extension that wraps create, update, upsert and delete, reads the row before an update or delete inside the same transaction, writes an AuditLog row with before and after, logs createMany, updateMany and deleteMany as one row holding the filter, and never logs writes to AuditLog itself. Keep the exported prisma type and the globalThis cache. Extend post.test.ts to assert a create row after post.add and an update row with before and after after a direct update. Run pnpm prebuild, pnpm test-unit, pnpm tsc and pnpm lint until they pass, then open a pull request that explains what each action records and which operations are logged as a filter.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds the `AuditLog` model to `prisma/schema.prisma`, a new directory under `prisma/migrations/` with its `CREATE TABLE` and two `CREATE INDEX` statements, the extension in `src/server/prisma.ts`, and the new assertions in `src/server/routers/post.test.ts`. Its description shows the migration SQL, lists which operations write a full before-and-after row and which write a filter row, and quotes the `test-unit`, `tsc` and `lint` output from the sandbox.

The router files do not change, which the description states plainly: because the extension lives on the client, every current and future model is covered without touching `post.ts`, and the `defaultPostSelect` that keeps extra fields out of API responses is untouched.

Before merging, a reviewer decides who the `actor` should be once the app has sessions (the starter's `createContextInner` returns an empty context today), whether `before` and `after` should be trimmed for large rows, and how long rows are kept, since the model has a `createdAt` index ready for a retention job.

## Run it on every model that holds customer data

A team whose Prisma projects each need the same log sends this body once per repository from its own server, each `POST /o/{org}/sessions` with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own schema: a project with a `User` model and sessions in its tRPC context gets the `actor` filled from the context, and one on SQLite gets the `Json` columns written as `String` with the reason in the pull request.

After the first merge, an automation on the Project with a `linear` trigger on `linear.issue.labeled`, `audit` in `config.labels`, and the prompt "this issue names a model or an operation the audit log must also cover; extend the extension and its test and open a pull request" starts one run per labelled issue. The trigger adds the issue after the prompt and fills in nothing else.

## Why run it on Rush?

An audit log is easy to add in the wrong place: a few `create` calls in one router get a log line, the next router does not, and the gap is found during an incident. Putting it in a client extension covers every model in one file, but writing that extension correctly, with the read-before-write inside the transaction and the self-logging guard, takes a careful hour with Postgres running. The agent does that work in a sandbox with its own database, runs the same migration and test steps the workflow runs, and shows the output.

The migration SQL, the test run and the type check stay with the run, so a reviewer can see that `prisma migrate dev` produced exactly one new migration and that the extension type-checks against the project's Prisma version. A team with several Prisma services runs the same request across all of them at once.

## Frequently asked questions

### Does every router have to change to call the log?

No. The extension wraps the client in `src/server/prisma.ts`, so `prisma.post.create` in the router writes a log row without a code change there. New models and new routers are covered the moment they use the exported client.

### What about updateMany and deleteMany?

Prisma returns only a count for those, not the rows, so the extension writes one `AuditLog` row with the filter and the count rather than a before-and-after pair per row. The pull request lists this limit, and a reviewer can decide whether bulk paths should read the rows first.

### Will the migration run in CI?

Yes. `.github/workflows/main.yml` already starts a Postgres service and runs `pnpm prebuild`, which calls `prisma migrate deploy`, before the unit and end-to-end jobs. The new migration is applied there like the existing four, and the extended test runs against it.

### Who is recorded as the actor?

The starter has no sessions, so `actor` is nullable and left empty. The extension reads it from the tRPC context when one is present, and the pull request shows where to pass a user id once the app has authentication.

## More Prisma jobs

- [Add Connection Pooling Limits to a Prisma App on Serverless](https://getrush.ai/run/add-connection-pooling/prisma/)
- [Add Cursor Pagination to a Prisma API](https://getrush.ai/run/add-cursor-pagination/prisma/)
- [Add Database Indexes to a Prisma Schema](https://getrush.ai/run/add-database-indexes/prisma/)

## The same job on other stacks

- [Add an Audit Log to a Quarkus API](https://getrush.ai/run/add-audit-log/quarkus/)
- [Add an Audit Log to a Sequelize and Express API](https://getrush.ai/run/add-audit-log/sequelize/)
- [Add an Audit Log to a SQLModel App](https://getrush.ai/run/add-audit-log/sqlmodel/)

## Keep reading

- [What an agent can do in Prisma itself, once you connect it](https://getrush.ai/integrations/prisma/)
- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
