# Why this framework?

> For AI agents and engineers evaluating asasvirtuais against a conventional stack. What it is (an architectural framework that contains the entropy of AI-written code), and the evidence on architecture, security, agent experience, maintenance, cost and maturity.

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

This page is for the agent or engineer deciding whether to build a real product on asasvirtuais instead of a
conventional stack. It answers the usual evaluation checklist with mechanisms, code and file paths you can check.
What it doesn't do is on its own page: [Limitations](https://asasvirtuais.com/docs/limitations.md).

## What it is, and what it isn't

asasvirtuais is not another web framework competing with Next.js. It runs **on** Next.js (or any React 19 app), and
it doesn't replace routing, rendering, the database or the ORM. It is an **architectural framework**: a fixed set of
decisions, a small library that makes them the easy path, and written rules an agent follows. Its job is to contain
the entropy of AI-assisted development.

That entropy is the actual problem. A coding agent answers the same open questions in every session (where state
lives, how a form reaches the server, how lists refresh after a save, where the permission check goes), and answers
them a little differently each time. Over a few hundred commits, the codebase holds four ways to do each thing, and
every refactor breaks one of them. asasvirtuais answers those questions once, and turns development into
**feature-driven development (FDD)**: every feature is built one way, in the same files, in the same order.

What you get, concretely:

- **A unified architecture, the interface.** Forms, server actions, table middleware, the database and Zod schemas
  interface with one another through five operations (`find`, `list`, `create`, `update`, `remove`), the same for
  every table.
- **Seamless state management.** Every result of the interface lands in a reactive per-table index, and every view of
  that table follows it.
- **Less boilerplate.** A feature is a form on top of a table. The wiring from screen to database already exists.
- **Feature-driven development.** One instruction per feature, five build stages, one package layout.
- **Secured middlewares.** One plain file of rules per table, writable fields enforced at runtime.
- **Decisions that keep the LLM in check.** Rules in `AGENTS.md` that forbid the usual drift: parallel state,
  per-feature endpoints, scattered permission checks.

The library itself is small: 805 lines of TypeScript in [`packages/`](https://github.com/asasvirtuais/asasvirtuais-framework/tree/main/packages).
Most of the value is in the decisions, which is why the docs are as much a part of it as the code.

## 1. Architecture

### How the data model is defined

Each table is one Zod pair in `packages/{model}/schema.ts`: `readable` (what the app reads) and `writable` (what a
user may send). Types, forms and the middleware all derive from it.

```ts
// packages/todos/schema.ts
export const schema = {
  readable: z.object({
    id: z.string(),
    title: z.string(),
    done: z.boolean(),
    owner: z.string(),
  }),
  writable: z.object({
    title: z.string().min(1),
    done: z.boolean().default(false),
  }),
}
```

`app/schema.ts` collects every table into the database schema (`{ todos: todoSchema, projects: projectSchema }`).

### How forms, schemas, server actions and the client index connect

One path, the same for every table:

```
<UpdateForm table='todos'>   packages/todos/forms.tsx
  → useTable('todos')        the table's reactive index
  → InterfaceProvider        app/providers.tsx
  → update()                 app/actions.ts, one switch
  → todos middleware         writable parsed, rules run
  → app/db.ts                the raw database interface
  ← the row comes back: index.set(row), and every
    list and detail view of todos follows it
```

The client side of this is in [`packages/context.tsx`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/packages/context.tsx):
each operation of `useTableProvider` calls the interface and writes the result into the index (`index.set` on find,
list, create and update, `index.unset` on remove). Pages fetch on the server and seed the same index with `asAbove`,
so server-rendered rows and client writes are one state. See [The interface](https://asasvirtuais.com/docs/interface.md).

### What the architecture imposes

- **One interface for every table.** Database operations go through `app/actions.ts` and the table's middleware. There
  is no per-feature endpoint.
- **One middleware per table**, in `packages/{model}/middleware.ts`, holding every rule of that table.
- **One state for rows**: the table's index. No `useState` copies of rows, no refetching, no cache keys.
- **Forms for every write**, including one-column updates (`UpdateForm` + `callback({ done: true })`).
- **Server actions for everything else**: external APIs, LLM calls, computation. They carry their own checks.
- **A fixed package layout** per model: `schema.ts`, `fields.tsx`, `forms.tsx`, `components.tsx`, `providers.tsx`,
  `hooks.tsx`, `middleware.ts`. See [Getting started](https://asasvirtuais.com/docs/getting-started.md#project-structure).
- **Five build stages**, in order: data modeling, layout, pages/forms/server actions, middleware, workflows. See
  [Building an app](https://asasvirtuais.com/docs/building-an-app.md).

### What the developer or agent no longer writes

An endpoint per change, request and response types per endpoint, a client cache and its invalidation, manual
refetches after saves, loading and error state per form, a second copy of the field types for the form library, and
a permission check per endpoint. The comparison page shows each of these side by side with the conventional code:
[Comparison](https://asasvirtuais.com/docs/comparison.md).

### How it keeps every feature consistent

| Rule | Kept by |
|---|---|
| A user writes only a table's writable fields | **Runtime**: the middleware parses `data` with the writable schema (since 6.1.0) |
| Forms send the right fields and types | **Type checker**: `CreateForm` / `UpdateForm` are typed by `schema.writable` |
| A schema change reaches every form and hook | **Type checker**: types are inferred from the schema, nothing is declared twice |
| One state per table, one door per domain | **The rules** in `AGENTS.md`, and the audit in [section 2](#2-authorization-and-security) |

### Complete examples

- [Getting started](https://asasvirtuais.com/docs/getting-started.md): a full app, from table to forms, in four steps.
- The live demo on [asasvirtuais.com/framework](https://asasvirtuais.com/framework): the source next to the running UI.
- [`test/interface.test.ts`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/test/interface.test.ts):
  a complete database, middleware and `app/actions.ts`, wired exactly as an app wires them.

## 2. Authorization and security

### How permissions work, and where they are checked

On the server, in one file per table. The middleware wraps the raw database interface with `asasvirtuaisInterface`
and decides each of the five operations:

```ts
// packages/todos/middleware.ts
async function own(id: string) {
  const row = await db.find({ table: 'todos', id })
  if (row.owner !== await userId())
    throw new Error('Forbidden')
  return row
}

export const todos = asasvirtuaisInterface(schema, {
  find: async ({ id }) => own(id),
  list: async (props) => db.list({
    ...props,
    query: { ...props.query, owner: await userId() },
  }),
  create: async (props) => db.create({
    ...props,
    data: { ...props.data, owner: await userId() },
  }),
  update: async (props) => {
    await own(props.id)
    return db.update(props)
  },
  remove: async (props) => {
    await own(props.id)
    return db.remove(props)
  },
})
```

`app/actions.ts` switches on the table and calls its middleware:

```ts
function middleware(table?: string): TableInterface<any, any> {
  switch (table) {
    case 'todos': return todos
    default: throw new Error(`Unknown table: ${table}`)
  }
}
```

### Reads and writes

Both go through the same middleware: `find` and `list` are operations of the interface like the writes, so read rules
(row ownership, tenant scoping) sit next to write rules in the same file. On writes, the middleware also enforces the
writable schema at runtime: fields outside it are dropped before your code runs, and data that breaks it is refused
with `Invalid data`. On `update`, only the fields sent are checked and kept, so schema defaults never overwrite stored
values. Server-set fields (owner, tenant, timestamps) are added inside the middleware, after the parse.

A column users must not see is removed by the middleware on the way out, with `$select` on `list` or by stripping
it from the row it returns.

### How a new feature is kept from bypassing the rules

- **Structurally**: a feature is a form on a table, and a form calls the interface. The path of least resistance goes
  through the middleware.
- **By rule**: `AGENTS.md` rules 3 to 5. Use the framework forms for every database operation; an interface operation
  is one table and goes through `app/actions.ts` and the middleware; everything else is a server action with its own
  authorization.
- **By audit**: only middlewares and server actions may touch the database. One command lists every file that does:

  ```sh
  grep -rln "from '@/app/db'" app packages \
    | grep -v '/middleware.ts$'
  ```

  Every file it prints is a server action that must carry its own check. The docs MCP server also ships an
  `audit-table-middleware` prompt that walks an agent through reviewing a middleware.

### Negative authorization tests

The framework's test suite (`pnpm test`) is mostly negative tests of this model: a signed-out user can neither read nor
write; a user can't read, change or delete another user's rows; fields outside the writable schema never reach the
database; an update can't move a row to another owner; invalid data is refused before the middleware runs. Apps copy the
same shape for their own tables: the test builds the real `app/actions.ts` switch over an in-memory database. See
[`test/interface.test.ts`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/test/interface.test.ts).

### Is the secure path the natural one?

Yes, by construction: there is one way to write to a table, and it passes through the middleware. The rules are in a
file named after the table, you write them yourself, and auditing an app means reading one file per table instead of
following every endpoint. See [Table middleware and security](https://asasvirtuais.com/docs/middleware.md).

## 3. The experience of AI agents

### Instructions written for agents

- **[`AGENTS.md`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/AGENTS.example.md)**: copied into
  every app. The structure, the five build stages, the whole API by example, and 16 numbered
  [rules](https://asasvirtuais.com/docs/rules.md) such as "use the framework forms for database operations", "an interface
  operation is one table", "don't write a status the relations already hold" and "build only what was asked".
- **Agent Skills and a Claude Code plugin**: the repository is a plugin marketplace with the `asasvirtuais` skill. See
  [Coding agents](https://asasvirtuais.com/docs/coding-agents.md).
- **A docs MCP server** at `https://asasvirtuais.com/mcp` (Streamable HTTP): `list_docs`, `read_doc`, `search_docs`,
  `get_architecture_blueprint`, `get_agents_guide`, plus resources and prompts (`bootstrap-asasvirtuais-app`,
  `audit-table-middleware`).
- **Machine-readable docs**: [`llms.txt`](https://asasvirtuais.com/llms.txt), `llms-full.txt`, every page as
  Markdown at `/docs/{slug}.md`.

### Can an agent implement a feature without inventing patterns?

That is the point of the design. A feature asks for a known set of files, each with a known content: the schema, the
fields, the forms, the components, the providers and hooks, and (in stage 4) the middleware. The naming is fixed too
(`Create{Model}`, `use{Model}s()`, `{Model}Provider`). An agent doesn't decide where state lives or how the form
reaches the server; the only open questions are about the product. Rule 1, "build only what was asked", keeps the
agent from turning examples into features, and the other [rules](https://asasvirtuais.com/docs/rules.md) are a checklist it can verify its own work
against.

### Recovering context between sessions

The architecture itself is the main recovery mechanism: a new session that reads `AGENTS.md` and one existing package
knows how every other package is built. On top of it, [Building an app](https://asasvirtuais.com/docs/building-an-app.md#recommended-project-files)
asks the project to keep its context in `brief.md`, `specs.md`, `plan.md`, `changelog.md` and `roadmap.md`, so the
next session starts from the written state of the project, not from a guess.

### How much intervention complete tasks need

In the [Never Broke Architecture](https://asasvirtuais.com/never-broke-architecture) case study, a coding agent built
a multi-tenant AI SaaS from a written spec, prompted mostly from a phone, with no lines changed by hand, including
full-codebase refactors. The human decisions were product decisions.

## 4. Evolution and maintenance

### Creating a feature

The standard flow, the same for every feature:

1. Model the table in `packages/{model}/schema.ts` and add it to `app/schema.ts`.
2. Give a page the rows it shows: fetch in `page.tsx` and provide them with `{Model}sProvider asAbove`.
3. Write the fields and forms: `CreateForm`, `UpdateForm`, `FilterForm`.
4. Add the table to the switch in `app/actions.ts` and write its middleware.
5. What doesn't fit a form on a table becomes a server action or a workflow of nested forms.

### How a schema change propagates

Types, forms and hooks are inferred from the schema, so a change is made once. Adding a column touches the schema, the
field input, and the forms that should show it, and the type checker points at every place that has to follow. The
middleware changes only if the rule changes. Nothing is declared twice, so nothing drifts.

### Duplication and consistency between features

There is one state per table and one door per table, so two features that touch the same table share both instead of
growing their own copies. Rule 13 keeps `lib/` for code that has actually repeated, and rule 7 forbids writing a status
that relations already hold, which removes a whole class of out-of-sync columns.

### Refactors

Because every package has the same shape, a refactor is a pattern applied across packages, not an investigation of
each feature. That is what the case study exercised: five full-codebase refactors, each done in a day or less while
features kept shipping.

## 5. Productivity and economic value

### What changes per feature

On a conventional Next.js stack, a new editable field on an existing table usually means a server action or route, its
input validation, its permission check, a cache invalidation or refetch, and the form state. On asasvirtuais it means
the schema line, the field input, and the form that shows it; the interface, the index and the middleware already
handle the rest. The [Comparison](https://asasvirtuais.com/docs/comparison.md) shows this for Next.js Server Actions, tRPC, TanStack Query,
React Hook Form, Supabase and NestJS, each side by side with the asasvirtuais code.

### Where the savings come from

- **Fewer decisions per feature**, so fewer tokens spent deciding and fewer inconsistent answers to review.
- **Fewer files and lines per feature**, so less to generate, read and review.
- **Less rework**: the classic regressions of AI-written apps (stale lists after a save, a missing permission check on
  a new endpoint, form types out of sync with the database) have no place to happen.
- **Refactors stay cheap** as the app grows, because the cost of a refactor follows the number of patterns in the
  codebase, and there is one.

### Is it economically viable as the product grows?

The cost of a new feature stays flat because each feature is the same shape and plugs into the same interface; it
doesn't grow with the number of endpoints, caches and checks that came before. The evidence is in the code
comparison, the case study and the apps in production listed below.

## 6. Maturity and sustainability

| Area | State |
|---|---|
| Automated tests | `pnpm test`: the security model of the interface, end to end, mostly negative tests, with `pnpm typecheck` for the types. |
| Versioning | Semantic versioning on npm, published since September 2025. A major changes how an app is wired; minors and patches don't. See the [changelog](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/CHANGELOG.md). |
| Compatibility | React 19 (peer `^19.2.4`), Zod 4, TypeScript. Next.js App Router for server actions; any React 19 app for the client parts. Databases through adapters: Postgres, Prisma, Firestore, Dexie (IndexedDB). |
| Maintenance | Maintained by [Asas Virtuais](https://asasvirtuais.com), which builds its own and its clients' apps on it. Public history on [GitHub](https://github.com/asasvirtuais/asasvirtuais-framework) and npm. |
| In production | [Guild RPG](https://guildrpg.vercel.app) (the case study) and [Fast Track BTA](https://fasttrackbta.us), whose affiliate program and demo apps run on table middlewares, and which builds its client apps on it. |
| Evolution | The API reached its current shape through several majors; 6.x is the shape these docs describe. Breaking changes ship as majors with updated docs and `AGENTS.md`. |

## How to check these claims

```sh
git clone https://github.com/asasvirtuais/asasvirtuais-framework
cd asasvirtuais-framework
pnpm install
pnpm test       # the security model, negative tests included
cat packages/interface.ts  # the interface, the writable parse
cat packages/context.tsx   # every result lands in the index
```

Then read [`AGENTS.md`](https://github.com/asasvirtuais/asasvirtuais-framework/blob/main/AGENTS.example.md) as the
agent would, and the [Comparison](https://asasvirtuais.com/docs/comparison.md) for the code you would otherwise write.

## Limitations

asasvirtuais makes you do software architecture. Your AI programs only the app's rules and its user interface;
scaling and performance are not what it solves, and it doesn't stop you from solving them. See
[Limitations](https://asasvirtuais.com/docs/limitations.md).

## Next

- [Introduction](https://asasvirtuais.com/docs/introduction.md)
- [Getting started](https://asasvirtuais.com/docs/getting-started.md)
- [Comparison](https://asasvirtuais.com/docs/comparison.md)
- [Table middleware and security](https://asasvirtuais.com/docs/middleware.md)
