# The rules

> The 16 rules of AGENTS.md, explained with examples. Build only what was asked, forms for every database operation, one table per interface operation, pages that hand their data down, component directories, atomic packages.

Source: https://asasvirtuais.com/docs/rules

[`AGENTS.md`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/AGENTS.example.md) ends with 16
numbered rules. They are what a coding agent checks its work against, and what a reviewer checks the agent against.
This page explains each one, numbered as in the file. Copy the file into your app as `AGENTS.md`:

```sh
cp node_modules/asasvirtuais/AGENTS.example.md AGENTS.md
```

## 1. Build only what was asked

The examples in `AGENTS.md` and in these docs use a placeholder domain, `projects` and their `todos`. Their tables,
fields, screens and button labels show the API; they are not features. Features, steps, buttons and automations come
from the user's request, never from an example. An agent that adds a "Mark all done" button because the docs have a
toggle is inventing a feature.

## 2. Read records from their provider

Inside `{Model}Provider`, components read the record with `use{Model}()`. They don't receive the record, or its
fields, as props:

```tsx
// packages/todos/components.tsx
export function TodoItem() {
  const { single } = useTodo()
  return <li>{single.title} <ToggleTodo /></li>
}

// the list wraps each item in its provider
array.map(t => (
  <TodoProvider key={t.id} id={t.id}>
    <TodoItem />
  </TodoProvider>
))
```

The provider follows the table's index, so the item updates when any form changes that row. A prop would be a copy
that goes stale. See [The interface](https://asasvirtuais.com/docs/interface.md#one-record-singleprovider).

## 3. Use the framework forms for database operations

Every database operation is a table form (`CreateForm`, `UpdateForm`, `FilterForm`), including single-column updates.
A flag, a status or a name is an `UpdateForm` with one field, not a server action:

```tsx
export function ArchiveProject() {
  const { single } = useProject()
  return (
    <UpdateForm table='projects' schema={schema} id={single.id}>
      {archive => (
        <button disabled={archive.loading}
          onClick={() => archive.callback({ archived: true })}>
          Archive project
        </button>
      )}
    </UpdateForm>
  )
}
```

The reactive index updates the UI, so there are no `useState` copies of rows, no manual `set` calls and no
revalidation. See [Forms](https://asasvirtuais.com/docs/forms.md).

## 4. An interface operation is one table

It goes through `app/actions.ts` and the table's middleware, which centralizes the authorization of that table's
operations. Never put the mutation of other tables, or effects in the back-end (emails, external APIs, LLM calls),
into an interface operation or its middleware. See [Server code](https://asasvirtuais.com/docs/server-code.md#an-interface-operation-is-one-table)
and [Table middleware](https://asasvirtuais.com/docs/middleware.md).

## 5. Everything else is a server action

External APIs and calls, LLM calls and any other computation live in the `actions.tsx` of the component that uses
them, one call per action, wrapped with `action(...)`. They call `app/db.ts` without the middleware, so each one
carries its own authorization logic; repeated functions go into `lib/`. When the result should be saved, the action
returns it and a form saves it:

```tsx
// app/projects/[id]/components/summary/actions.tsx
'use server'
type Params = { text: string }
export const summarize = action(async ({ text }: Params) => {
  await requireUser()
  return llm.summarize(text)
})

// component.tsx: the inner form runs the action,
// the outer form saves its result
'use client'
import * as actions from './actions'
const { summarize } = unwrap(actions)

export function Summary() {
  const { single } = useProject()
  return (
    <UpdateForm table='projects' schema={schema} id={single.id}>
      {project => (
        <Form defaults={{ text: single.notes }} action={summarize}
          onResult={summary => project.callback({ summary })}>
          {summary => (
            <button onClick={summary.submit}
              disabled={summary.loading || project.loading}>
              Summarize
            </button>
          )}
        </Form>
      )}
    </UpdateForm>
  )
}
```

## 6. Complex operations only when clearly defined

Two tables are mutated in one operation only when the need is clear, in a server action written for it. Steps the user
takes are separate forms, and what follows a write starts in the client after the response. See
[Complex operations](https://asasvirtuais.com/docs/server-code.md#complex-operations).

## 7. Don't write a status the relations already hold

No column, and no update, for whether a table has related rows in another (`hasTodos`, `isEmpty`, `allDone`). The
relational database already holds it: read the related rows and show what they say. A stored copy drifts the first
time a write forgets to update it. See [Derived state](https://asasvirtuais.com/docs/server-code.md#derived-state-is-read-not-written).

## 8. Simple workflows are nested forms

A workflow the user follows on screen is nested `Form`s. The Vercel Workflow SDK is for workflows that run in the
back-end. See [Workflows](https://asasvirtuais.com/docs/workflows.md).

## 9. Fail fast, return errors

Throw `new Error('Unauthorized')` or `new Error('Forbidden')`, and call `notFound()` for missing records. Every server
action is wrapped with `action(...)`, client components call `unwrap(actions)`, and server code calling another action
uses `ok(await name(...))`. See [Errors](https://asasvirtuais.com/docs/interface.md#errors).

## 10. Pages hand their data down

`page.tsx` is a Server Component. It fetches the rows its components show, with `ok(await list(...))` or `find` from
`app/actions.ts`, and mounts each table's `{Model}sProvider` with them as `asAbove`:

```tsx
// app/projects/[id]/page.tsx
type Props = { params: Promise<{ id: string }> }

export default async function ProjectPage({ params }: Props) {
  const { id } = await params
  const project = ok(await find({ table: 'projects', id }))
  const query = { project: id }
  const todos = ok(await list({ table: 'todos', query }))
  return (
    <ProjectsProvider asAbove={single(project)}>
      <TodosProvider asAbove={index(todos)}>
        <ProjectProvider id={id}>
          <ProjectHeader />
          <Todos />
          <CreateTodo />
        </ProjectProvider>
      </TodosProvider>
    </ProjectsProvider>
  )
}
```

What follows from it:

- **A layout does the same** for the rows its own components show, so their `SingleProvider`s find them and fetch
  nothing.
- **Components don't fetch on mount.** They read `use{Model}s().array`, filtered, or `use{Model}()` under a
  `{Model}Provider`.
- **Each table is provided once, where its rows are fetched.** No empty providers kept around for safety. A table with
  nothing to show is provided without rows only around the form that writes to it.
- **Cache invalidation is avoided rather than handled.** The forms keep the index current. A write that doesn't go
  through a form sets or unsets its rows in `onSuccess` / `onResult`.
- **Writes from outside the subtree refresh the page.** A `{Model}sProvider` replaces its table only for its subtree,
  so a component outside it (a dialog in the layout, for example) that writes to that table calls `router.refresh()`,
  and the page's `asAbove` brings the row in.
- **`TablesProvider` is for tables a route keeps fetching.** It mounts tables without rows and leaves components to
  fetch them with `FilterForm`: data from outside sources, for example.
- **Real-time data** comes from a client context that receives the signals and passes them as `asAbove` to a
  `TableProvider`.
- **`context.tsx` holds state, not table providers.**
- **Shells shared by several pages** move up to their closest common `layout.tsx`.

## 11. Component directories

A page keeps its components in `components/` next to `page.tsx`, one lowercase directory per component, with only the
files it needs:

```
app/projects/[id]/
├── page.tsx
└── components/
    └── summary/
        ├── component.tsx  # 'use client': the UI
        ├── actions.tsx    # 'use server': its actions
        ├── index.tsx      # server: fetches, renders UI
        ├── cache.tsx      # 'use cache': cache params
        ├── context.tsx    # shared state, if needed
        └── hooks.tsx      # local state, if needed
```

- `component.tsx` is the client UI.
- `actions.tsx` holds the server actions that component calls.
- `index.tsx` is usually the high-level version of the component: it fetches on the server and renders
  `component.tsx`, often inside `Suspense`. It is never a barrel file: import each file from its own path.
- `cache.tsx` receives the params the cache depends on (from the URL, for example) and renders `index.tsx` with them,
  so caching is decided here rather than in the fetching layer.
- `context.tsx` and `hooks.tsx` hold shared and local state. Never table providers: tables come from
  `{Model}sProvider` with the rows the server fetched.

Code used only by a component stays in its directory. A component shared by several pages lives with their closest
common route.

## 12. Packages are atomic

`packages/{model}/` holds the schema, fields, forms, components, providers, hooks and middleware of one table, and
nothing about pages. Page composition lives in `app/`. See the
[project structure](https://asasvirtuais.com/docs/getting-started.md#project-structure).

## 13. `lib/` only for repeated code

A library is a small single file that appears once the same code repeats across several actions, such as the
`requireUser()` check of rule 5, or `index(rows)` and `single(row)` for `asAbove`. Nothing goes into `lib/` in
anticipation.

## 14. Trust the schema

Access guaranteed fields directly. A field the schema declares required is there: no `todo?.title ?? ''`. Fields that
can be missing are declared optional in the schema and given standard UI defaults.

## 15. Plain names and text

Contextual variable names: the render prop is named after what the form represents (`project`, `toggle`, `archive`),
not `form` or `props`. Simple UI text: "Create {Object}", "Update {Object}", "Delete {Object}", "Search", "Cancel".
The names of files, hooks, providers and forms follow the
[naming conventions](https://asasvirtuais.com/docs/building-an-app.md#naming-conventions).

## 16. Credit on commercial apps

If the app is commercial (sold, a paid service, earning revenue, or built for a paying client), it shows
`<a href='https://asasvirtuais.com'>Built with asasvirtuais</a>` where users can find it, such as the footer. It is
the condition of the free license; a commercial license without it is available from Asas Virtuais. See
[License and commercial use](https://asasvirtuais.com/docs/license.md).

## Next

- [Building an app](https://asasvirtuais.com/docs/building-an-app.md): the five stages the rules apply to
- [Coding agents](https://asasvirtuais.com/docs/coding-agents.md): giving your agent `AGENTS.md`
- [API reference](https://asasvirtuais.com/docs/api-reference.md)
