---
title: AI agents
description: "Give coding agents Active Record’s guide and rules."
seo:
  description: "Give coding agents Active Record’s guide and rules: llms.txt, llms-full.txt, every page as Markdown, the agent skill, and a pointer in AGENTS.md or CLAUDE.md."
---

:::tip
The agent skill gives your agent the guide and its rules, and is what most projects need. The rest are for agents that can’t load a skill, or for a pointer that’s always in context.
:::

## Giving your agent the docs

| Resource                                                 | What it is                                                                                                                                    |
| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| [`llms.txt`](/llms.txt)                                  | An index of the guide, each page with what it covers, following [llmstxt.org](https://llmstxt.org). Start here when an agent can fetch pages. |
| [`llms-full.txt`](/llms-full.txt)                        | The whole guide in one Markdown file.                                                                                                         |
| Any page + `.md`                                         | Every page as Markdown: [`/associations.md`](/associations.md).                                                                               |
| `/.well-known/agent-skills/active-record/SKILL.md`       | The skill below, published where agents look for a site’s skills.                                                                             |
| `node_modules/@forestfuture/active-record/llms-full.txt` | The same guide, shipped in the package. It matches the version you’ve installed, and an agent can read it without fetching anything.          |

## Installing the agent skill

Install the library’s [agent skill](https://github.com/forestfuture/active-record/blob/main/packages/active-record/skills/active-record/SKILL.md): its rules, the shapes of a Model and a Worker, and the mistakes to watch for, with pointers into the guide. Agents that support skills, such as Claude Code, Cursor, Codex, and [others](https://skills.sh), load it when they work on Active Record code:

```sh
npx skills add forestfuture/active-record
```

To install the copy shipped with your installed version, sync skills from `node_modules`:

```sh
npx skills experimental_sync
```

:::note
The skills CLI marks `experimental_sync` as experimental, so its name may change.
:::

## Pointing AGENTS.md at the guide

Agents read `AGENTS.md`, or `CLAUDE.md` for Claude Code, at the start of every task, while a skill loads only when the agent decides it applies. To make sure the guide is always in reach, add one line to yours:

```md
Before writing code with `@forestfuture/active-record`, read the part of `node_modules/@forestfuture/active-record/llms-full.txt` for the task.
```

The line names the guide shipped with your installed version, so it stays correct after an upgrade.

## Using the rules without a skill

Skip this section if you’ve installed the skill: the block below is the skill’s rules, and the agent would read them twice. For an agent that reads only `AGENTS.md` or `CLAUDE.md`, paste it into yours:

```md

Active Record (`@forestfuture/active-record`) is a Rails-style Active Record for Cloudflare Workers, with an adapter per database inside it: `@forestfuture/active-record/d1` for D1, and `@forestfuture/active-record/postgresql` for Postgres, which needs the app's own `pg`. Import Models, Relations, and errors from the core, and what opens a database from its adapter's entry: `connect`, `withSession`, `NoSession`, and `d1` from `/d1`; `connect` and `postgresql` from `/postgresql`. Every `active-record` command reads `active-record.jsonc`, which names each database's adapter, so one project can hold a D1 database and a Postgres one: run `npx active-record init` to write it, never `--adapter` on another command (`init --adapter postgresql` adds Hyperdrive bindings to a file that names only D1 databases). Its guide for the installed version is `node_modules/@forestfuture/active-record/llms-full.txt`, one Markdown file with a `#` heading per page: read the part for the task before writing code with it.

- Create tables with the generators, never by hand-declaring attributes: `npx active-record g model Post user:references 'title:string!'` writes the migration and the Model; `npx active-record g migration AddSlugToPosts slug:string:unique` writes a change. Apply them with `npx active-record migrate`. After a hand-written migration, run `npx active-record schema`. Never edit the generated `src/db/schema.ts`.
- A Model extends the app's base class: `class Post extends ApplicationRecord {}`. Its table comes from its class name (`Post` → `posts`), or `static override table = "…"`, and its attributes from the schema, so it declares only behavior. With a bundler that renames classes (Wrangler keeps them by default), set `static override modelName = "Post"` on each Model, so its table, foreign keys and schema entry keep the name. Run `npx active-record schema` after adding or renaming a Model, as after a migration: a Model it hasn't seen throws `InvalidModel`. Change how a column is read with an override in the class, `static override attributes = { metadata: "json" } as const`, never by editing the schema. Normalize an attribute's values (trimming, lowercasing an email) with `this.normalizes("email", { with: (email) => email.trim().toLowerCase() })` in `static {}`, not in a setter, a `beforeValidation` callback or each query: it runs on every assigned value and on a query's values too, so `findBy` with the user's input finds the stored row. It doesn't change rows already stored: normalize those with `record.normalizeAttribute("email")` and `save()`. A value a form sends but the table doesn't keep (a terms checkbox, a confirmation) is a virtual attribute in the same object, `termsOfService: { type: "boolean", virtual: true }`, not a plain class field: it's cast, tracked and taken by `permit`, never saved, and a query can't name it. To give an attribute a second name, add `title: { aliasOf: "name" }` there, rather than a getter and setter: queries, writes and validations take either name. Keep a password as `password: { securePassword: true }` there, with a `password_digest` column, never by hashing in a callback or storing it: it's hashed with PBKDF2 when the record is saved, `await user.authenticate(password)` checks it, and sign in with `await User.authenticateBy({ email, password })`, which resolves to null for a wrong email or password alike, rather than `findBy` then `authenticate`. Ask for the current password before a change with `passwordChallenge`. For bcrypt or a stronger hash, give `{ securePassword: { algorithm } }` an object with `hash`, `verify` and `maxBytes`. The default costs 10–40 ms of CPU per hash, past the Workers Free plan's 10 ms. A random token for each new record (an API token, an invite code) is `authToken: { secureToken: true }` on a string column with a UNIQUE index, with `await user.regenerateAuthToken()` to replace it, rather than `crypto.randomUUID()` in a callback; `generateSecureToken()` makes one for anything else. For a password reset link, use `await user.passwordResetToken()` and `await User.findByPasswordResetToken(token)`, never a token column you store and clear: it lasts 15 minutes and stops working once the password changes. For any other link (confirming an email, unsubscribing), declare `this.generatesTokenFor("emailConfirmation", { expiresIn: { days: 1 }, dependsOn: (user) => user.email })` in `static {}`, then `await user.generateTokenFor(purpose)` and `User.findByTokenFor(purpose, token)`; or sign an id with `await user.signedId({ purpose, expiresIn })` and `User.findSigned(signedId, { purpose })`. Don't put a plain id in such a link, or sign one yourself. They're signed with the Worker's `SECRET_KEY_BASE` (`wrangler secret put SECRET_KEY_BASE`, at least 32 bytes; in tests, `process.env`); to rotate it, override `static signingSecret(env)` on the app's base class to return `[env.SECRET_KEY_BASE, env.PREVIOUS_SECRET_KEY_BASE]`. An `INTEGER` holding a Unix time (Drizzle's `timestamp` modes) is `{ type: "datetime", storage: "unixSeconds" }` or `"unixMilliseconds"`. Bytes are a `binary` attribute (a `Uint8Array`, in a `BLOB` or `bytea` column): assign a form's file as `new Uint8Array(await file.arrayBuffer())`. An exact number (a price, a quantity with a fraction) is a `decimal` attribute, held as text (`"12.5"`) in a `NUMERIC` or `DECIMAL` column, never a `real`, with `precision` and `scale` to round it as `NUMERIC(10, 2)` does; a day with no time is a `date` (`"2026-01-02"`) and a time of day a `time` (`"09:30:00"`), assigned as text, not a `Date`. A value no built-in type holds (money, a value object, a list kept as text) is a custom type: `const money = defineType({ storedAs: "integer", cast, serialize, deserialize })`, given as `priceCents: money` in the override or in `define`, rather than converting in getters, setters or callbacks; its `cast` throws for a value it can't hold. A column with a fixed set of values is an enum: `status: { enum: ["draft", "published"] }` (names stored as text) or `{ enum: { low: 0, high: 1 } }` (an integer column), which gives `post.isDraft()`, `await post.saveAsPublished()`, `Post.published()`, `Post.notPublished()` and `Post.enumValues("status")`; use those and `where({ status: "published" })` rather than a hand-written scope or a `declare status: …` narrowing. Run `npx active-record schema` after adding an enum, so its scopes are typed. A column the database restricts to a list (a Postgres enum type, `CHECK (state IN ('open', 'done'))`) already has the names in the schema, typed and checked but without methods: turn them on with `state: { enum: true }`, rather than listing the names again, or drop it with `enum: false`. An unlisted stored value reads as `null`; rename a name with `{ newName: "old_value" }`. A cell that isn't its attribute's type (a number in an ISO `datetime`, text in an `integer`) fails the load with a `TypeError` naming the attribute: correct the override, don't catch it.
- Start queries and new records from the Model, as in Rails: `User.find(id)`, `User.where(…)`, `User.build(…)`. Each Model queries the binding named in the generated schema its base class holds, during a request. For a D1 Session, wrap the handler in `withSession(request, env.DB, fn)`. For per-request `onQuery`, or tests and scripts outside a Worker, wrap the code once in `withDatabase(connect(env.DB, { … }), fn)`. Records keep the database they came from.
- Never pass a request's whole body, form or query string to a Model: name the fields, with destructuring or `User.permit(await request.json(), "email", "name")` (it reads `FormData` and `URLSearchParams` too). Assigned values are checked against the attribute's type, but that doesn't stop a user setting `role` or `isAdmin`. Check a request value's type before querying with it: `findBy({ token: null })` matches rows whose token is NULL, and a list matches any of its values. `findOrCreateBy`, `findOrInitializeBy` and `createOrFindBy` throw `TypeError` for a list, a comparison or a `sql` fragment.
- Name attributes in camelCase everywhere: `where`, `order`, `pluck`, `foreignKey`. Column names (snake_case) appear only inside `sql` fragments.
- Write custom SQL as an `sql` tagged template, which binds every value: ``where(sql`lower(${column("email")}) = ${email}`)``. Interpolate an attribute's value with `column("publishedAt").value(date)`, not the bare `Date`, when the attribute is stored as a Unix time: a bare `Date` is ISO text, and it throws `TypeError` when it's compared directly with that column.
- For a raw `env.DB.prepare(…).bind(…)` statement, bind `Post.typeForAttribute("publishedAt").serialize(date)`, which writes the value as the attribute stores it, and read a cell with `.deserialize(cell)`. A value the attribute can't hold throws `TypeError`.
- Bulk writes run when called, without callbacks: `await posts.deleteAll()`, `deleteBy({…})` and `updateAll(…)` resolve to how many rows; `insert(…)`, `insertAll`, `upsert` and `upsertAll` to `{ rowsAffected, rows }`, where `rows` holds each written row's primary key, or the attributes `returning: [...]` names (`returning: false` for none). Through a Relation they write its equality values and `createWith` over the attributes given (`Post.where({ userId: 1 }).insert({ userId: 2, … })` writes `userId: 1`), where `build` and `create` keep the given ones. Make several writes atomic by preparing them in one batch's callback: `batch((b) => [b.insert(Post, {…}), b.updateAll(Post.where(…), {…}), b.save(user), b.destroy(post)])`. The callback can't await, so load what the writes need first. D1 has no interactive transactions, so a read-then-write can't be atomic.
- Count with the database, not in memory: `post.incrementColumn("viewCount")` or `Post.updateCounters(id, { viewCount: 1 })` add to the row atomically, where `post.viewCount++` then `save()` loses another request's increment. The counter statics (`Post.updateCounters(ids, …)`, `incrementCounter`) skip the default scope, so with a key from a request, and a default scope that separates tenants or hides deleted rows, write `Post.where({ id }).updateCounters({ … })`, which keeps it. The `…Column` methods and `updateColumns` skip validations, callbacks and `updatedAt`, so use `update` for a change those should see; `increment` and `toggle` only change the record in memory. In an after-callback, `record.isPreviouslyNewRecord()` says whether the save created it.
- To mark a record changed without saving it (a cache key, a "last seen"), `await record.touch()` sets `updatedAt`, or `touch("lastSeenAt")` that attribute too, with no validation or save callback; `Post.where(…).touchAll()` touches many rows. A touch runs `afterTouch` and the update commit callbacks (`afterUpdateCommit` included), so code there that should run only on a save belongs in `afterUpdate` or `afterSave`. To keep a parent's `updatedAt` current as its children change (a cache key), declare `belongsTo(Article, { touch: true })` on the child rather than touching the parent in a callback: the parent is touched in the child's batch, runs its own touch callbacks, and touches its own parents in turn. A parent that isn't loaded costs one SELECT per level, so preload the chain (`includes({ article: "blog" })`) when saving many. `hasOne(Profile, { touch: true })` touches a user's profile the same way when the user is updated, destroyed or touched. For a bulk import, wrap it in `Article.noTouching(async () => { … })`, so no article is touched per comment, then touch each article once after it.
- To show how many records an association has, keep a counter cache rather than counting on each read: `article = belongsTo(Article, { counterCache: true })` with a `commentsCount` attribute, which `article.comments().size()` reads. Saves, destroys and the association's `delete`/`clear`/`deleteAll()` keep it; bulk writes (`insertAll`, `updateAll`, a Relation's `deleteAll`) don't, so follow them with `Article.resetCounters(id, "comments")`. Add one to existing rows with `{ active: false }`, reset each, then drop `active: false`.
- To work through more records than a request should hold (a backfill, an export, a cleanup), iterate in batches rather than `toArray()` or `offset` pages: `for await (const user of User.where(…).findEach())`, `findInBatches()` for arrays, and `inBatches()` for a Relation per batch to `updateAll`, `deleteAll` or `destroyAll`. Batches go in primary-key order, so `reorder()` a Relation that has an order (a default scope's too), and bound them with `start` and `finish`, not `offset`. On D1 a Worker invocation sends at most 1,000 queries (50 on Free), and each batch sends one (`inBatches` reads its keys, then sends the write, and a `destroyAll` adds a load and each record's dependent reads; a `db.batch` counts as one): split a larger job across invocations by `start` and `finish`.
- To destroy many records with their callbacks and `dependent:` strategies, use `posts.destroyAll()`, `Post.destroyBy({…})` or `Post.destroy(ids)`: they load the records and destroy them in one write, all or none (`RecordNotDestroyed` if one refuses). They hold every record in memory, so destroy a large set a batch at a time: `for await (const batch of posts.inBatches({ batchSize: 100 })) await batch.destroyAll()`.
- Keep the generators' `TEXT` keys, generated in code, for records saved together (`--id integer` gives a key D1 generates instead). An owner whose key is known before its INSERT (generated in code, or already saved) is written in one atomic batch with the records built through it on its database. A key D1 generates exists only after its own write, so each level is then written in a separate batch. Records on another database are always a separate write there, and a batch refuses them.
- To change how those keys are made (UUIDv7, ULID, a prefix), override `static generateId` once on the app's base class; don't give each Model's key a `default`. `generateId` sees only the attribute's name, so a value made from other attributes (a slug) goes in a callback.
- Declare associations as fields, passing the target class: `posts = hasMany(Post, { dependent: "destroy" })`, `author = belongsTo(User)`. The field's name is the association's name. Add and remove a `hasMany`'s records through it: `user.posts().push(post)`, `delete(post)` (by its `dependent:`, nullifying by default), `destroy(post)` and `clear()`, rather than writing the foreign key yourself, so a loaded collection stays in step. Saving requires a `belongsTo`'s record ("must exist"), so pass `optional: true` when its foreign key may be `null`. Its target may be on another database (a Model on another base class): reading, preloading (one more round trip), and writing through it go to the target's database, and a save or destroy writes each database separately, not atomically. A `hasOne`'s new record, through `set`, `build` or `create`, replaces the old one, which its `dependent:` strategy removes (without one, its foreign key is set to `null`). Await `user.profile.set(profile)`: on a saved owner it saves at once, unlike a `belongsTo`'s `set`. To save changes to associated records with their owner, declare the association `autosave: true` and change the records it loaded (`await user.posts().toArray()`), not ones found with a query of their own. `record.markForDestruction()` then destroys a record when its owner is saved. For a record that can belong to one of several Models, list them: `commentable = belongsTo([Post, Photo])`, with `commentableType` and `commentableId` attributes, and `comments = hasMany(Comment, { as: "commentable" })` on each listed Model. Point it with `comment.commentable.set(post)`, not by writing the type yourself: the type holds each Model's `modelName`, so set `static modelName` on the listed Models if a bundler renames classes. Reach records through a join Model with `through`: `projects = hasMany(Project, { through: "assignments" })` (`source:` names the join Model's association when it isn't `project`). It reads and preloads as any association, each record once. Write through it to make and remove join records: `user.projects().push(project)`, `build`, `create`, `delete(project)` and `clear()` (`destroy(project)` destroys the join records too, not the project). A built project is linked when the owner is saved, not the project. Don't narrow before `deleteAll` (`user.projects().where(…).deleteAll()`), which deletes the projects themselves. Only a join Model is written through (a `hasMany` to a `belongsTo`); `insert` and `upsert` through it throw. An upsert through a `hasMany` only updates the owner's records, and leaves another owner's clashing row as it is.
- Change the copy of validation messages with `this.errorMessages({...})` in the `static {}` block of the app's base class (every Model) or a Model (`attributes: { email: { taken: "…" } }` for one attribute), and attribute names with `this.humanAttributeNames({...})`, rather than a `message` on every `validates`. Check a value typed twice with `this.validates("email", { confirmation: true })` and a virtual `emailConfirmation: { type: "string", virtual: true }`; `toJSON()` leaves the confirmation out. Compare one attribute with another with `comparison: { greaterThan: (event) => event.startsAt }`, not a callback. Validate an association's loaded records with `this.validatesAssociated("posts")`, not a callback. Run a rule only when creating or updating with `on: "create"` or `on: "update"` (or skip one with `exceptOn`), not `if: (record) => record.isNewRecord()`. For a step of the app's own, list its name in the Model's `static validationContexts = ["signup"] as const` and validate in it with `isValid("signup")` or `save({ context: "signup" })`; that replaces `"create"`, so pass `["create", "signup"]` to run both. For a custom error, `errors.add("startsAt", { type: "onTheHour" })` and give `onTheHour` a message there.
- Check what writes return. `save()` and `update()` resolve to `false` when validation fails (reasons in `record.errors`) or a callback aborts (`record.abortReason`). `destroy()` resolves to `false` when a callback aborts, or a `restrictWithError` association refuses (reason in `record.errors`). The `…OrThrow` methods throw instead. Constraint errors, such as `RecordNotUnique`, always throw, and so does a rule declared `strict: true` (`StrictValidationFailed`), meant for values only a bug could set.

```

Copy it again after upgrading Active Record, since the rules can change.
