# @frontierjs/litestone

> SQLite ORM for Bun — schema-first, type-safe, no third-party dependencies

Latest version **1.1.22** (published 2026-11-19) · MIT license · 0 weekly downloads

## Install

```sh
npm install @frontierjs/litestone
pnpm add @frontierjs/litestone
yarn add @frontierjs/litestone
bun add @frontierjs/litestone
```

Provides the command `litestone`.

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 1.1.22 |
| Published | 2026-11-19 |
| First published | 2026-03-07 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 5.3 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | FrontierJS |
| Maintainers | jdkdev |
| Keywords | sqlite, bun, orm, database, schema, migrations, query-builder, type-safe, litestream, json-schema, row-level-security, policies, soft-delete, fts5 |

## Links

- npm: https://www.npmjs.com/package/@frontierjs/litestone
- Repository: https://github.com/frontierjs/litestone
- npm.io page: https://npm.io/package/@frontierjs/litestone

## Dependencies (1)

- [@frontierjs/toolbelt](https://npm.io/package/@frontierjs/toolbelt.md) 0.1.15

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 1.1.22 (latest) — 2026-11-19
- 1.1.20 — 2026-11-18
- 1.1.16 — 2026-11-05
- 1.1.15 — 2026-11-05
- 1.1.13 — 2026-11-02
- 1.1.12 — 2026-10-30
- 1.1.11 — 2026-10-27
- 1.1.10 — 2026-10-20
- 1.1.9 — 2026-09-18
- 1.1.8 — 2026-09-13
- 1.1.7 — 2026-09-10
- 1.1.6 — 2026-09-08
- 1.1.5 — 2026-08-16
- 1.1.4 — 2026-08-14
- 1.1.0 — 2026-08-02
- … 4 more at https://npm.io/package/@frontierjs/litestone/versions

## README

# Litestone

**Schema-first SQLite ORM for Bun.**

A single `.lite` file declares the **shape** of your data, **access** rules, **lifecycle** behavior, and the **generation** of everything downstream — TypeScript types, migrations, JSON Schema, runtime enforcement. Edit the schema; everything stays consistent. SQLite and Bun keep the runtime embedded and fast, with no third-party dependency.

```lite
// schema.lite
type Address {
  street     String
  city       String
  postalCode String
}

trait Dates {
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model User {
  id      Int @id
  name    String
  email   String  @email
  address Json  @type(Address)

  @@trait(Dates)
  @@allow(read,   auth() != null)
  @@allow(update, id == auth().id)
}
```

```js
// One declaration produces a typed, validated, access-controlled client
const db   = await createClient({ path: './schema.lite', db: './app.db' })
const mine = db.$setAuth({ id: 1 })            // every policy grades this principal

await mine.user.create({ data: { id: 1, name: 'Ann', email: 'ann@example.com',
  address: { street: '1 Main St', city: 'Boston', postalCode: '02101' } } })

const me = await mine.user.findUnique({ where: { id: 1 } })
me.address.city                                // typed as string

await mine.user.findMany({
  where: { address: { city: 'Boston' } }       // compiles to json_extract
})
```

---

## Why

In most stacks, your data model is described in five places — an ORM schema, a validator library, TypeScript types, middleware for access control, JSON Schema for API consumers — and they drift.

Litestone collapses that to one `.lite` file. Row-level policies, traits, typed JSON, soft delete with cascade, encryption, audit trails, multi-database routing, full-text search — all declared in the schema, enforced at runtime, and reflected in generated types.

The runtime is implementation detail in service of the declarative model. SQLite is the target so the database is a single file you can back up, replicate, ship in a container, or run in a Bun script. Bun is the runtime because its native SQLite driver removes the C++/WASM hop other ORMs need.

Both choices are deliberate. Both keep the principles intact: **fast, embedded, single-binary, no external services to run alongside your app.**

---

## How it compares

The comparison is organized around what you can **declare** in the schema and what derives from those declarations.

### Shape — what you can declare about your data

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **Schema as a file (not code)** | ✓ | ✗ | ✓ | ✓ |
| **Multi-file schema imports** | ✓ | ✗ ¹ | ✓ | ✓ |
| **Relations + nested writes + includes** | ✓ | ✓ | ✓ | ✓ |
| **Field validators in schema** (`@email`, `@regex`, `@length`, etc.) | ✓ | ✗ | ✗ | ✓ ¹⁴ |
| **Reusable model traits** (cross-cutting concerns spliced as fields) | ✓ | ✗ | ✗ | ✓ ⁶ |
| **Typed JSON columns** (write-time validation + path filter pushdown) | ✓ | partial ⁷ | partial ⁷ | partial ⁷ |
| **Derived relation fields** (`@from(Model, sum: amount)`) | ✓ | ✗ | ✗ | ✗ |
| **Computed fields** (`@computed`) | ✓ | ✗ | ✗ | ✗ |
| **Generated columns** (`@generated("expr")`) | ✓ | ✓ | ✗ | ✗ |
| **State machines** (`@@transitions`, enforced at the data boundary) | ✓ | ✗ | ✗ | ✗ |
| **Authorized transitions** (`@gate(5)` per move, and it reaches the client) | ✓ | ✗ | ✗ | ✗ |
| **Full-text search** (FTS5 declared with `@@fts`) | ✓ | ✗ | ✗ | ✗ |
| **`@@external`** (declare a table you don't own) | ✓ | ✗ | partial ⁴ | ✗ |
| **Composite primary keys** (`@@id([a, b])`, key order preserved) | ✓ | ✓ | ✓ | ✓ |
| **Partial indexes and partial uniques** (`where:` on `@@index` / `@@unique`) | ✓ | ✓ | partial ¹³ | ✗ |
| **Cross-column constraints** (`@@check`, enforced by the table) | ✓ | ✓ | ✗ | partial ⁸ |
| **Wide integers** (`Int @big` — exact past 2⁵³, end to end) | ✓ | ✓ | ✓ | ✓ |
| **Declared value sets** (`valueset` / `@values`, with a stated order) | ✓ | ✗ | ✗ | ✗ |
| **Polymorphic parent** (`@@arc` — one child, several possible parents) | ✓ | ✗ | ✗ | partial ⁹ |
| **Tenant-declared columns** (`@@extensible` — keys a customer adds at runtime) | ✓ | ✗ | ✗ | ✗ |
| **Views declared in the schema** (`view` + `@@sql`, with access attributes) | ✓ | partial ¹⁰ | partial ¹⁰ | partial ¹⁰ |
| **Materialized views with a declared refresh trigger** (`@@refreshOn`) | ✓ | ✗ ¹¹ | ✗ | ✗ |
| **STRICT mode by default** | ✓ | ✗ | ✗ | ✗ |

### Access — who can do what to which rows and fields

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **Row-level policies** (compiled to SQL WHERE) | ✓ | partial ¹² | ✗ | ✓ |
| **Field-level policies** | ✓ | ✗ | ✗ | ✓ ¹⁶ |
| **`auth()` in policy expressions** | ✓ | ✗ | ✗ | ✓ |
| **Relation-based policy checks** | ✓ | ✗ | ✗ | ✓ |
| **Level-based access control** (GatePlugin) | ✓ | ✗ | ✗ | ✗ |
| **Field-level encryption at rest** (`@encrypted` / `@secret`) | ✓ | ✗ | ✗ | ✗ |
| **Guarded fields** (`@guarded`) | ✓ | ✗ | ✗ | ✗ |
| **System-mode bypass** (`asSystem()`) | ✓ | ✗ | ✗ | ✓ ¹⁵ |

### Lifecycle — what happens automatically over a row's life

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **Auto timestamps** (`@default(now())`, `@updatedAt`) | ✓ | ✓ | ✓ | ✓ |
| **Soft delete built-in** | ✓ | ✗ | ✗ | ✓ ² |
| **Cascading soft delete** | ✓ | ✗ | ✗ | ✗ |
| **`@hardDelete` overrides for cascade** | ✓ | ✗ | ✗ | ✗ |
| **`@keep` — children that outlive a soft-deleted parent** | ✓ | ✗ | ✗ | ✗ |
| **Document sealing** (`@seals` / `@sealed` / `@immutable`, over the closure) | ✓ | ✗ | ✗ | ✗ |
| **Auto attribution** (`@default(auth().id)`, `@updatedBy`) | ✓ | ✗ | ✗ | partial ⁶ |
| **Per-scope sequences** (`@sequence(scope: tenantId)`) | ✓ | ✗ | ✗ | ✗ |
| **File storage lifecycle** (S3/R2 upload + cleanup paired with row writes) | ✓ | ✗ | ✗ | ✗ |
| **Audit trail per write** (`@@trail(audit)` with full diff) | ✓ | ✗ | ✗ | ✗ |
| **Encryption key rotation** (`$rotateKey`) | ✓ | ✗ | ✗ | ✗ |

### Querying — how you read the data back

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **Type-safe client** | ✓ | ✓ | ✓ | ✓ |
| **Cursor pagination** | ✓ | ✓ | ✓ | ✓ |
| **Aggregate / groupBy / count** | ✓ | ✓ | ✓ | ✓ |
| **Raw SQL escape hatch** | ✓ | ✓ | ✓ | ✓ |
| **Recursive CTE tree queries** | ✓ | manual | manual | manual |
| **Window functions** (`ROW_NUMBER`, `LAG`, rolling aggregates) | ✓ | manual | manual | manual |
| **FTS5 `search()`** | ✓ | ✗ | ✗ | ✗ |
| **Per-model `query(spec)` dispatcher** (auto-routes by spec shape) | ✓ | ✗ | ✗ | ✗ |
| **Multi-model batch `db.query(spec)`** (one transaction, named results) | ✓ | ✗ | ✗ | ✗ |
| **Reusable scopes** (named query fragments, chainable, auth-aware) | ✓ | ✗ | ✗ | ✗ |
| **JSON path filter pushdown** (`where: { addr: { city: 'X' } }`) | ✓ | ✗ | ✗ | ✗ |
| **Governed bulk extract** (`@@export` — a paginated scoped read, not a dump) | ✓ | ✗ | ✗ | ✗ |

### Operations — running this in production

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **`onQuery` query logging** | ✓ | ✓ | ✓ | ✓ |
| **Studio browser UI** | ✓ | ✓ | ✓ | ✓ |
| **`db push` (autoMigrate)** | ✓ | ✓ | ✓ | ✓ |
| **Multi-database support** | ✓ | ✓ | ✓ | ✓ |
| **Multi-database in one schema** | ✓ | ✗ | ✗ | ✗ |
| **Continuous WAL replication** (Litestream wrapper) | ✓ | ✗ | ✗ | ✗ |
| **`$backup` / `$walStatus`** | ✓ | ✗ | ✗ | ✗ |
| **Per-model storage backend** (SQLite + JSONL append-only) | ✓ | ✗ | ✗ | ✗ |
| **Application-level locks** (`$lock`) | ✓ | ✗ | ✗ | ✗ |
| **First-class multi-tenant client cache** | ✓ | ✗ | ✗ | plugin |
| **Migrations without an external dev database** | ✓ | ✓ | ✗ | ✗ |
| **Managed connection pooling** | ✗ | ✗ | ✓ ³ | ✓ ³ |

### Generation — what derives from the schema

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **TypeScript types** | ✓ | ✓ | ✓ | ✓ |
| **JSON Schema** (with `$defs` for typed JSON) | ✓ | ✗ | partial | partial |
| **Migration files** | ✓ | ✓ | ✓ | ✓ |
| **Test factories** (auto from schema) | ✓ | ✗ | ✗ | ✗ |
| **Test fixtures** (`generateGateMatrix`, `generateValidationCases`) | ✓ | ✗ | ✗ | ✗ |
| **Reverse introspection** (DB → `.lite`) | ✓ | ✓ | ✓ | ✓ |
| **Adoption from a foreign schema** (Prisma, Rails, Frappe, raw SQL) | ✓ | ✗ | ✗ | ✗ |
| **A graded gap report on adoption** (`changed` / `lost` / `noted`, per line) | ✓ | ✗ | ✗ | ✗ |
| **Schema mutation testing** (`litestone mutate` — a survivor is a hole) | ✓ | ✗ | ✗ | ✗ |
| **Auto-generated API / tRPC hooks** | ✗ | ✗ | ✗ | ✓ |
| **No third-party npm dependencies** | ✓ | ✓ | ✗ | ✗ |

### Platform reach (a tradeoff, not a feature)

|  | Litestone | Drizzle | Prisma | ZenStack |
|---|:---:|:---:|:---:|:---:|
| **Database support** | SQLite | PostgreSQL, MySQL, SQLite, D1, etc. | PostgreSQL, MySQL, SQLite, MongoDB, etc. | PostgreSQL, MySQL, SQLite ⁶ |
| **Runtime support** | Bun | Node, Bun, Deno, Cloudflare Workers, edge | Node, Bun, edge ⁵ | Node, Bun |

<sub>Competitor columns last read against their live docs on **2026-10-16**, and only for the rows named in the next paragraph. Every other competitor cell predates that and is from memory of the 2026-04 to 2026-08 releases — treat a ✗ in those columns as "last checked then", not "checked now". The Litestone column is graded against this tree, so it needs no date.</sub>

<sub>Re-read 2026-10-16: Drizzle — generated columns (SQLite), RLS policies, views and materialized views, Prisma — partial indexes, views, materialized views, multi-file schema, edge runtimes, check constraints / generated columns / RLS (none documented). ZenStack v3 — runtime base, supported databases, field validators, multi-file import, soft delete, views, and the row-level, field-level and `auth()` policy cells plus the bypass. Second pass, same day — Drizzle: `$type<T>()` typing and the absence of runtime checks, `check()` on SQLite tables, Zod validators derived from a table, STRICT (not documented on the SQLite column-types page). Prisma: typed JSON (third-party generators only), validators (none in the schema language), STRICT (not documented on the SQLite page). ZenStack v3: typed JSON, `@@index` (no `where`), `@@check` (none in the attribute reference), runtimes (no v3 statement beyond a Bun SQLite dialect), STRICT (not documented). Not re-read: `@@arc`/polymorphism beyond `@@delegate`, JSON sub-key filtering in ZenStack, and any STRICT cell beyond the pages named. A new dated entry here is the unit of re-verification; do not bump the date for a row that was not re-read.</sub>

¹ Drizzle schema is TypeScript code — you can split it across files using normal JS imports, but there is no dedicated schema import declaration like `import "./models/users.lite"`. Multi-file is a code organization choice, not a language feature.

² ZenStack v3 ships soft delete as a plugin (`@zenstackhq/plugin-soft-delete`, since v3.8.0, preview): a nullable `DateTime? @deletedAt` field, deletes rewritten to updates and reads filtered. It does not cascade, and a plain `@unique` still collides with a soft-deleted row until you add a partial unique index by hand in a manual migration (2026-10-16). Older ZenStack material shows a `@@deny(read, deleted)` policy instead; that pattern predates the plugin.

³ Via Prisma Accelerate / ZenStack Cloud — managed external services, not part of the local ORM.

⁴ Prisma supports `@@ignore` to exclude a model from the client, and `prisma db pull` can introspect external tables — but there is no first-class way to query an externally-managed table through the Prisma client with full type safety.

⁵ Prisma's edge story moves every release. As of 2026-10-16 its docs list Cloudflare Workers and Vercel Edge through driver adapters as **Preview, compatible drivers only**, and Deno Deploy as "not yet". The earlier "Accelerate or specific drivers" wording was not re-confirmed.

⁶ ZenStack v3 is a different implementation from v2: it is built on Kysely with no runtime dependency on Prisma (2026-10-16), so "inherits Prisma's" no longer describes its databases or runtimes. Its docs list PostgreSQL, MySQL and SQLite, through a Kysely dialect you pass in; they name no runtime (Bun appears only as a package manager and, in a docs pull request, via the community `kysely-bun-sqlite` dialect), so the runtime cell is still from memory. ZenStack v3 introduced `type X / model M with X` for column splicing — equivalent to Litestone's `trait` / `@@trait(T)`. Multi-file schemas use an explicit `import "./user"` (the `.zmodel` extension is appended), merged into one AST before generation (2026-10-16).

⁷ Drizzle's `$type<T>()` and Prisma's third-party typed-JSON generators (`prisma-json-types-generator`) provide TypeScript types only — Drizzle's docs say it "won't check runtime values" and the generator's own README claims no runtime enforcement (2026-10-16). Filter operations on JSON sub-keys require dropping into raw SQL. ZenStack v3 declares the shape in ZModel (`type` + `@json`) and validates a write against it, but loosely by default: unknown keys pass unless the type carries `@@strict` (since v3.9.2), and its docs say nothing of filtering by sub-key (2026-10-16). Litestone validates the shape on every write and lets you filter inside typed JSON columns using the same query shape you'd use on real columns (`where: { address: { city: 'NYC' } }` compiles to `json_extract(...)`).

⁸ ZenStack's `@@validate` refuses a bad row at the application layer. `@@check` is a table constraint in the emitted DDL, so a write that never goes through the client is refused too. ZenStack's attribute reference lists no check-constraint attribute, and its `@@index` takes no `where` (2026-10-16).

⁹ ZenStack models polymorphism as delegated inheritance — one child type per parent. `@@arc` is the other direction: one child row whose parent may be any of several models, resolved by a discriminator column.

¹⁰ Drizzle and Prisma can both declare a view (Prisma's is the `views` preview feature), and ZenStack v3 has a `view` block too, in preview: no `@id` or index, and the migration engine does not create it. Its docs do not say whether a policy applies to a view (2026-10-16). What none of them carries is access on the projection: a Litestone `view` takes `@@gate` and `@@allow` of its own, so a projection can be gated ABOVE the rows it aggregates.

¹¹ Drizzle exposes Postgres materialized views; the refresh is a command you issue (`db.refreshMaterializedView`). Prisma documents no materialized-view support; you create one by hand and refresh it with raw SQL. `@@refreshOn` declares which writes rebuild it.

¹² Drizzle declares Row-Level Security with `pgPolicy`, but only for Postgres tables (with Neon and Supabase helpers), and it is the database that enforces it. There is no SQLite equivalent, no per-field policy, and no `auth()` in the schema.

¹³ Prisma accepts `where` on `@@index` / `@@unique` behind the `partialIndexes` preview feature, on PostgreSQL, SQLite, SQL Server and CockroachDB, not MySQL.

¹⁴ ZenStack v3 has `@length`, `@email`, `@url`, `@regex`, `@startsWith`, `@gt` and the like, plus a multi-field `@@validate`, run through Zod on the ORM's mutation APIs. They are not enforced through its query builder (2026-10-16).

¹⁵ ZenStack's policy engine is a plugin: `db.$use(new PolicyPlugin())` returns a new, enforced client, and the raw `db` you installed it on stays unrestricted. That unrestricted client is its system-mode bypass.

¹⁶ ZenStack field-level policies are a preview feature (since v3.2.0): `@allow` / `@deny` on a field for `read` and `update` only, not on relation or computed fields. A failed read returns `null` for that field; a failed update rejects the whole write.

**When to choose the others instead:**

- **Drizzle** — you need Postgres or MySQL; you want schema-as-code with full TypeScript inference; you prefer a thin query builder over a higher-level ORM
- **Prisma** — largest ecosystem, most tutorials, strongest hiring pool; you need Prisma Accelerate (managed connection pooling + edge caching); you're already invested in the Prisma ecosystem
- **ZenStack** — you want auto-generated tRPC or REST APIs from your schema; you're building on Prisma and want access control layered on top

---

## Install

```bash
bun add @frontierjs/litestone
```

The CLI also compiles to a dependency-free executable for machines without Bun — see [Standalone binary](#standalone-binary).

---

## Quick start

```bash
bunx litestone init              # create schema.lite + litestone.config.js
bunx litestone migrate create initial
bunx litestone migrate apply
bunx litestone studio            # browser UI at http://localhost:5502
```

---

### Where the schema lives in a FrontierJS app

Litestone is usable standalone — put the `.lite` file wherever you like. Inside a
FrontierJS app it has one home: **`db/schema.lite` at the app root**, a sibling of `api/`
and `web/` and inside neither.

```
my-app/
├── db/               ← this package's territory
│   ├── schema.lite   ← the single source of truth
│   ├── migrations/
│   └── backups/
├── api/              ← Junction reads the schema from here
└── web/              ← Sierra's build reads the same file
```

Both realms read that one file, so it belongs above both of them. Sierra's schema
auto-detection looks for `../db/schema.lite` from its own root for exactly this reason.
The full layout is in the [root README](../../README.md#project-structure).

---

## Schema

Schemas live in a `.lite` file. Syntax is close to Prisma's SDL with SQLite-native additions.

```lite
database audit { path "./audit/"; driver trail }   // where @@trail(audit) writes

enum Plan { starter  pro  enterprise }
enum Role { admin  member  viewer }

function slug(text: String): String {
  @@expr("lower(trim(replace({text}, ' ', '-')))")
}

model Account {
  id        Int  @id
  name      String
  slug      String   @slug(name)         // schema function → STORED generated column
  plan      Plan     @default(starter)
  meta      Json?
  createdAt DateTime @default(now())

  @@index([slug])
  @@gate(2.5.5.6)
}

model User {
  id          Int   @id
  account     Account   @relation(fields: [accountId], references: [id], onDelete: Cascade)
  accountId   Int
  email       String      @unique @email @lower
  name        String?     @trim
  role        Role      @default(member)
  salary      Float?     @allow(read, auth().role == 'admin')   // field-level policy
  apiKey      String?     @secret                                   // encrypted + guarded + audited
  deletedAt   DateTime?

  @@softDelete
  @@index([accountId, email])
  @@allow(read,   accountId == auth().accountId)
  @@allow(update, id == auth().id || auth().role == 'admin')
  @@trail(audit)                           // write-audit every create/update/delete
}
```

### Types

| Schema type | SQLite | JS |
|---|---|---|
| `Int` | `INTEGER` | `number` |
| `Float` | `REAL` | `number` |
| `String` | `TEXT` | `string` |
| `Boolean` | `INTEGER` 0/1 | `boolean` (auto-coerced) |
| `DateTime` | `TEXT` ISO-8601 | `string` |
| `Json` | `TEXT` | `object` (auto-parsed) |
| `Bytes` | `BLOB` | `Uint8Array` |
| `File` | `TEXT` JSON ref | stored in S3/R2/local via FileStorage plugin |
| `File[]` | `TEXT` JSON array | multiple files, each ref stored in S3/R2/local |
| `EnumName` | `TEXT` + CHECK | `string` |
| `Type[]` | `TEXT` JSON | `Array` (auto-parsed) |
| `Type?` | nullable | `null` when absent |

### Field attributes

```
@id                              primary key (auto-increment for Int)
@unique                          UNIQUE constraint
@default(value)                  now(), uuid(), ulid(), cuid(), nanoid(), true, "string", 42, enumValue
@default(auth().id)              stamped at write time from ctx.auth
@default(fieldName)              copy sibling field value on create
@relation(fields, references, onDelete?)
@generated("sql expr")           VIRTUAL or STORED generated column
@computed                        derived field — implement in computed.js, not stored in DB
@derived(expr)                   computed in SQL from this row's own columns, so unlike
                                 @computed it can be FILTERED and SORTED by. See below
@updatedAt                       auto-set to now() on every UPDATE
@updatedBy                       stamp ctx.auth.id on every UPDATE
@updatedBy(auth().field)         stamp custom auth field on every UPDATE
@createdBy                       stamp ctx.auth.id on CREATE. A stamp, not a default —
                                 the principal beats a caller-supplied value, and it is
                                 skipped entirely when ctx.auth is null
@createdBy(auth().field)         stamp custom auth field on CREATE
@version                         optimistic concurrency. See below
@sequence(scope: field)          per-scope auto-increment (e.g. per-account doc numbers)
@map("column_name")              custom DB column name
@omit                            excluded from findMany/findFirst
@omit(all)                       excluded everywhere
@system                          the application writes it, its caller does not. Readable by
                                 anyone, refused by name on every write. See below
@guarded                         excluded unless asSystem() — refused on write too, and an
                                 explicit select cannot unlock the read
@encrypted                       AES-256-GCM at rest — hidden from a non-system read, and
                                 still WRITABLE by a non-system caller
@encrypted(deterministic: true)  encrypted equality search — hidden from a non-system read
                                 like any @encrypted, and still ciphertext, so it re-keys
@hashed                          HMAC-SHA256, one-way — matchable, never readable
@secret                          @encrypted + @guarded + @trail(audit) + $rotateKey
@secret(rotate: false)           the same but excluded from key rotation — and therefore
                                 unreadable after one. $rotateKey refuses while one exists
@allow(read|'write'|'all', expr)   field-level conditional visibility
@trail(dbName)                     field-level audit trail to a trail database
@keepVersions                    on File? / File[]: skip old S3 object cleanup on update
@accept("mime/type")             on File / File[]: validate content type before upload
@syntax(sql)                     the text is in this syntax — md, sql, js, html… (picks the editor; no validation)
@label("Customer")               human-readable name → JSON Schema `title`, and the label a
                                 generated form renders
@hardDelete                      force hard delete even on @@softDelete models
@from(Model, count: true)        derived count from a relation (not stored in DB) — Int
@from(Model, sum: field)         derived sum/max/min from a relation — sum/max/min take a field
@from(Model, last: true)         first/last related ROW — field is typed Model?
@from(Model, exists: true)       Boolean
@from(Model, count: true, where: expr, orderBy: field)  filtered / ordered derived field
@from(Model, count: true, withDeleted: true, withTemplates: true)  opt back into the target's
                                 soft-deleted / template rows. By DEFAULT a @from reads its
                                 target the way the target is read — both out

// Validators — run on every create + update
@email  @url  @date  @datetime  @phone  @regex(pattern)
@length(min, max)  @gt(n)  @gte(n)  @lt(n)  @lte(n)
@startsWith(s)  @endsWith(s)  @contains(s)
@minItems(n)  @maxItems(n)  @uniqueItems     // arrays — and the value must BE an array,
                                             // with Int[]/String[] elements of that type

// Transforms — applied before validation + write
@trim  @lower  @upper  @slug
```

**Every validator takes an optional trailing message** — `@length(3, 20, "A reference is 3 to 20 characters")`, `@gte(0, "Totals cannot be negative")`, `@email("...")`. One authored string reaches all three realms: `generateJsonSchema` emits it as `x-messages`, keyed both by rule name *and* by the JSON Schema keyword the rule compiles to, so the API and the browser look up the keyword they just failed and say the sentence the schema declared.

`@required("msg")` is the wording for the required rule and **does not make a field required** — the absence of `?` does. On an optional field it is a parse error, because the message could never fire.

### Model attributes

```
@@softDelete                     enable soft delete (requires deletedAt DateTime?)
@@softDelete(cascade)            + cascade remove/restore to FK children
@@hasTemplates                   definition-vs-instance: adds isTemplate Boolean @default(false).
                                 Every read AND write excludes templates unless given
                                 withTemplates / onlyTemplates
@@hasTemplates(field: "isPreset")  the same, under a name you choose
@@fts([field1, field2])          FTS5 full-text search virtual table
@@index([col1, col2])            composite index
@@unique([col1, col2])           composite unique constraint
@@gate(R.C.U.D)                level-based access control — read.create.update.delete
@@allow(read|'create'|'update'|'delete'|'write'|'all', expr)  row-level policy
@@allow(read|..., expr, "custom error message")
@@deny(read|..., expr)         row-level deny (always wins over allow)
@@deny(read|..., expr, "custom error message")
@@scope(name, expr)              a named predicate in the @@allow expression language, asked
                                 for as `where: { $scope: 'name' }`. See below
@@transitions(field, ...)        a state machine on an enum field, enforced at the Data
                                 boundary. `name:` optional, `@gate(N)` per move. See below
@@trail(dbName)                    model-level audit trail: every write fires a log entry
@@auth                           marks model as the auth subject
@@createdBy                      sugar: adds createdById @createdBy + a createdBy relation
                                 to the @@auth model. @@createdBy(owner) renames the pair
@@updatedBy                      the same pair for updates
@@tenant(none)                   under `tenancy { strategy row }`: this model spans tenants
@@tenant(column: "accountId")    …or is scoped by a column of its own
@@noStrict                       opt out of SQLite STRICT mode (on by default)
@@map("table_name")              custom DB table name
@@db(dbName)                     assign model to a named database block
@@external                       table managed outside Litestone — queryable but skip DDL/migrations
```

---

## Relations

`@relation` goes on the **belongsTo** side, the model that holds the foreign key. The other side
(`User[]`, `Post[]`) is inferred and takes no attribute. A relation field names the MODEL, never a
table or a plural. Two `Tag[]`/`Post[]` fields facing each other make an implicit many-to-many with
no join model to write.

```lite
model Account {
  id    Int    @id
  name  String
  users User[]
}

model User {
  id        Int     @id
  email     String
  account   Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
  accountId Int
  posts     Post[]
}

model Post {
  id       Int    @id
  title    String
  author   User   @relation(fields: [authorId], references: [id])
  authorId Int
  tags     Tag[]
}

model Tag {
  id    Int    @id
  label String
  posts Post[]
}
```

`include` loads a relation with the read, to any depth, and `select` narrows what comes back:

```js
await db.account.create({ data: { id: 1, name: 'Acme' } })

// A nested write creates the children after the parent, in one call
await db.user.create({ data: { email: 'ann@example.com', accountId: 1,
  posts: { create: [{ title: 'Hello', tags: { create: [{ label: 'intro' }] } }] } } })

const posts = await db.post.findMany({
  include: { author: { include: { account: true } }, tags: { select: { label: true } } },
})
// posts[0].author.account → { id: 1, name: 'Acme' }
// posts[0].tags           → [{ label: 'intro' }]

// A count without loading the rows
await db.post.findMany({ include: { _count: true } })   // [0]._count → { tags: 1 }

// Sort by a related column, or by a relation aggregate
await db.post.findMany({ orderBy: { author: { email: 'asc' } } })
await db.user.findMany({ orderBy: { posts: { _count: 'desc' } } })
```

`connect` and `disconnect` on an update link existing rows, and a `where` reaches through a
relation with `is` on a to-one and `some`/`every`/`none` on a to-many
(`where: { author: { is: { email: 'ann@example.com' } } }`). Every read through a relation
applies the related model's own filters and policies, so `include` cannot reach a row a direct
read would not. One-to-one, `@@relator`, `@from`, relation `orderBy` and recursive trees are in
[docs/relations.md](./docs/relations.md).

---

## Multi-database

Route models to separate SQLite files, JSONL logs, or auto-schema audit trails:

```lite
database main      { path env("MAIN_DB", "./app.db") }
database analytics { path env("ANALYTICS_DB", "./analytics.db") }
database logs      { path "./logs/"; driver jsonl; retention 30d }
database audit     { path "./audit/"; driver trail; retention 90d }

model PageView {
  id        Int  @id
  path      String
  duration  Int
  createdAt DateTime @default(now())
  @@db(analytics)

  @@gate(0)
}

model ApiRequest {
  method  String
  path    String
  status  Int
  @@db(logs)     // append-only JSONL — no migrations, no schema changes
}
```

```js
// Single createClient — routes automatically
const db = await createClient({ path: './schema.lite' })

await db.pageView.create({ data: { path: '/home', duration: 142 } })  // → analytics.db
await db.apiRequest.create({ data: { method: 'GET', path: '/', status: 200 } })  // → logs/
await db.asSystem().auditTrail.findMany({ where: { model: 'User' } })  // → audit/ — system-only
```

**Drivers:**
- `sqlite` (default) — standard SQLite file with full ORM support
- `jsonl` — append-only log files, one `.jsonl` per model, `findMany` supported
- `trail` — auto-schema audit trail, receives `@trail` / `@@trail` entries; queries via `db.asSystem().auditTrail` — the trail is readable in a system context only

---

## Multi-tenancy

**Declared in the schema, one block, two strategies.** At most one per schema, and
it may not arrive through an import — only the app knows what its own tenants are.

**`strategy database`** is one SQLite file per tenant plus a registry that indexes
them:

```lite
tenancy {
  strategy database
  dir      "./tenants"
  registry "./tenants-registry.db"
  maxOpen  100
  resolve  subdomain               // subdomain | header("X-Tenant-Id") | claim(field)
}

model User { id Int @id  email String }
```

`key env("TENANT_KEY")` names the per-tenant encryption key's variable, and the
registry refuses to open while it is unset.

```js
const tenants = await createTenantRegistry({ path: './schema.lite', migrationsDir: './migrations' })
await tenants.create('acme')
const db = await tenants.get('acme')               // one tenant's client
await tenants.query(db => db.user.count())         // every tenant → [{ tenantId, result }]
await tenants.migrate()                            // every tenant, from migrationsDir
```

**`strategy row`** is one database and a tenant column, and it **desugars into
`@@deny`, never `@@allow`**. That is the whole subtlety: allows are OR'd within an
operation, so an allow added to a model that already declares one *widens* every
read to the entire tenant — the opposite of the feature. It is two rules per
scoped model, because `checkCreatePolicy` runs **before** the
`@default(auth().<claim>)` stamp: on create the column is legitimately absent, and
on read a row holding no tenant belongs to nobody.

```lite
tenancy {
  strategy row
  column   workspaceId
  claim    workspaceId             // default: the column
}

model Project { id Int @id  workspaceId Int  name String }
model Plan    { id Int @id  code String  @@tenant(none) }        // spans tenants
model Invoice { id Int @id  accountId Int  @@tenant(column: "accountId") }
```

A model declaring neither is **reported by name at parse**, once. `jsonl` and
`trail` models are never scoped — there is no policy engine there — and those
databases stay schema-global under `strategy database` too.

**Every reader asks one resolution** — `resolveTenancy(schema)`, reachable as
`db.$tenancy` and `registry.tenancy` — and precedence is **option → declaration →
default**. That is what stops `litestone tenant create` and the running app
disagreeing about where a tenant lives. `asSystem()` is the only way across a
tenant boundary, which is what a cross-tenant tier is built on.

`registry.tenantFor({ host, headers, principal })` applies the declared `resolve`.
Junction's `createApp({ tenants })` calls exactly that rather than carrying a
second reading of it. Full reference: [`docs/multi-tenancy.md`](./docs/multi-tenancy.md).

```bash
litestone tenant list | create <id> | delete <id> | migrate
```

---

## @@external — querying tables Litestone doesn't own

`@@external` marks a model whose table is managed outside Litestone — a SQLite view, an FTS5 virtual table, a table created by a migration tool, or a shared table from another process. Litestone skips DDL and migrations for it entirely, but exposes full query support: `findMany`, `findFirst`, `count`, `exists`, `aggregate`, `search`, etc.

```lite
model User {
  id        Int @id
  email     String
  name      String?
  accountId Int
  deletedAt DateTime?
  @@softDelete
}

// SQLite view — created manually or in a .sql migration
model active_users {
  id        Int @id
  email     String
  name      String?
  accountId Int
  @@external
}

model Post {
  id       Int @id
  authorId Int
  author   active_users @relation(fields: [authorId], references: [id])
}

// FTS5 virtual table managed by a third-party tool
model docs_fts {
  rowid   Int @id
  title   String
  body    String
  @@external
  @@fts([title, body])
  @@label(title)
}

// Table owned by another migration tool (e.g. a legacy schema)
model legacy_audit_log {
  id        Int  @id
  action    String
  actorId   Int
  createdAt DateTime
  @@external
}
```

```js
// What the .sql migration below does — a view Litestone never emits DDL for
await db.sql`CREATE VIEW IF NOT EXISTS active_users AS
  SELECT id, email, name, accountId FROM user WHERE deletedAt IS NULL`

// Fully queryable — all read ops work
const users = await db.active_users.findMany({ where: { accountId: 1 } })
const n     = await db.active_users.count()
const found = await db.active_users.exists({ where: { email: 'alice@example.com' } })

// Works with include — other models can still relate to @@external models
const posts = await db.post.findMany({ include: { author: true } })

// @@external models are excluded from autoMigrate and litestone migrate create
// — Litestone will never emit CREATE TABLE, ALTER TABLE, or DROP for them
```

**Common patterns:**

A SQLite view is the most useful form — define the view in a `.sql` migration, then query it through the ORM with full type safety:

```sql
-- migrations/20240101000000_create-active-users-view.sql
CREATE VIEW IF NOT EXISTS active_users AS
SELECT id, email, name, accountId
FROM user
WHERE deletedAt IS NULL;
```

```lite
model active_users {
  id        Int @id
  email     String
  name      String?
  accountId Int
  @@external
}
```

This is also how you expose read-only projections, denormalized reporting tables, or cross-database `ATTACH`ed tables through the Litestone query API without any migration risk.

---

## createClient

```js
import { createClient, parseFile } from '@frontierjs/litestone'

// A schema file, and the path of its main database
const db = await createClient({ path: './schema.lite', db: './app.db' })

// Pre-parsed — one parse, several clients
const parsed = parseFile('./schema.lite')
const second = await createClient({ parsed, db: ':memory:' })
```

`schema:` is the schema TEXT — an editor buffer, a template literal — and
`path:` is a file. A schema declaring its own `database` blocks needs no `db:`.

```js fragment
const db = await createClient({ path: './schema.lite',
  db:         './app.db',
  databases:  ':memory:',                 // or { main: { path } } — see the note below
  encryptionKey: process.env.ENC_KEY,     // 64 HEX characters = 32 bytes
  computed: './db/computed.js',
  plugins:    [new GatePlugin({ getLevel }), FileStorage({ provider: 'r2', ... })],
  onQuery:    (e) => logger.debug(e),          // production query logging
  hooks: {
    before: { setters: [fn], update: [fn], all: [fn] },
    after:  { getters: [fn], all: [fn] },
  },
  onEvent: { create: fn, update: fn, remove: fn, change: fn },
  filters: { post: { status: 'published' } },   // keyed by ACCESSOR (db.post), not model name
  scopes:  { Customer: CustomerScopes },        // named query fragments — see Scopes
  announce: 'collection',                       // the floor for a bulk write's event
  readOnly: true,                               // every SQLite database, read-only
  placeModels: { Session: 'sessions' },         // this client keeps Session in its own database
  now:      () => frozenDate,                   // the clock every time-dependent rule reads
  onLog: (entry, ctx) => ({ meta: { requestId: ctx.auth?.requestId } }),
})
```

**`db:` names MAIN's path and nothing else.** It overrides a declared
`database main`, so `db: ':memory:'` is the in-memory test client — but a
*second* declared database keeps its declared path regardless.
`databases: ':memory:'` is the shorthand that moves every one of them, jsonl and
trail included. Most specific wins:
`databases: ':memory:'` > `databases: { main: { path } }` > `db` > the declaration.

**`placeModels` moves models for one client and leaves the schema alone.**
Each named model is read and written in the named database. A database the
schema does not declare is declared for that client and needs a path from
`databases`; under `strategy database` the tenant registry puts it in the
tenant's file. A read-only copy uses it to keep `Session` writable while `main`
is readonly (`FJS-D1921`). A move that makes a relation cross databases is
refused, as it would be in the file.

**`encryptionKey` is parsed as hex**, so 64 *characters* is not necessarily 32
bytes — non-hex padding decodes short and is rejected with `must be 32 bytes`,
naming how many it got.

### Auth scoping

```js
const user   = { id: 1, role: 'member' }   // the request's principal
const userDb = db.$setAuth(user)           // scoped per request — policies + field rules apply
const sysDb  = db.asSystem()               // bypasses @@gate + @@allow/@@deny, unlocks @guarded fields
```

**`$setAuth` RETURNS a scoped client; it does not mutate.** `db.$setAuth(u)`
followed by `db.thing.create(…)` grades as anonymous, with no warning. It is
`const userDb = db.$setAuth(u)`.

**A client throws on an unknown property** — never `undefined`, so a typo'd
accessor is loud. The cost is that feature detection is itself a throwing
expression: `typeof db.$maybe === 'function'` explodes, and `'$maybe' in db` is
the question to ask.

### Raw SQL needs `asSystem()`

Once a schema declares any access rule — `@@gate`, `@@allow`/`@@deny` on a
model; `@guarded`, `@encrypted`, `@secret`, `@system`, `@scoped` or `@allow` on a
field — `db.sql` and `db.$setAuth(u).sql` **throw**:

```js fragment
db.asSystem().sql`SELECT …`                    // the deliberate bypass — and it can write
db.post.findMany({ where: { $raw: sql`…` } })  // keeps every policy — reach for this
```

Stored, operator-authored text is the case `sql` routes wrongly: it picks the
connection by the statement's first word, so a report opening `WITH` runs on the
writer and `WITH x AS (…) DELETE …` writes. `sql.read` refuses any write whatever
the first word is, and takes a tag or `(text, params[])` —
``await db.asSystem().sql.read(report.sql, [clientId])``, where a write throws an
error naming `sql.read`. It is raw SQL like `sql`, so it applies no access rule and is refused off
`asSystem()` under the same schemas. It limits what the statement may do, not
who may run it.

Raw statements enforce no gate, no row policy, no field guard and no soft-delete
filter, because all of those live above SQLite. It is coarse per schema on
purpose: deciding per statement means parsing it, and a wrong validator grants a
*false* guarantee. A data script run after `migrate apply` takes `asSystem()`.

---

## Row-level policies

`@@allow` and `@@deny` compile to SQL WHERE injections — filtering happens in SQLite, not JS:

```lite
model Post {
  id        Int  @id
  accountId Int
  status    String     @default("draft")

  // Default is open. First @@allow makes it deny-by-default for that operation.
  @@allow(read,   status == 'published' || accountId == auth().accountId)
  @@allow(create, accountId == auth().accountId)
  @@allow(update, accountId == auth().accountId)
  @@deny(delete,  status == 'published')   // published posts can never be deleted
}
```

```js
const userDb = db.$setAuth({ id: 1, accountId: 5 })

// Only returns posts where status='published' OR accountId=5
const posts = await userDb.post.findMany()

// Returns ALL posts — policies bypassed
const all = await db.asSystem().post.findMany()
```

**Policy expressions** support: `auth()`, `auth().field`, `now()`, comparison operators, `&&`, `||`, string/number/boolean literals, and `check(relatedModel, expr)` for relation-based checks.

---

## Access control — GatePlugin

Level-based access control. Assign levels 0–9, declare required levels per operation:

```lite
model Post {
  id Int @id
  @@gate(1.3.4.6)   // read=VISITOR, create=CREATOR, update=USER, delete=OWNER
}
```

```js
import { GatePlugin, LEVELS } from '@frontierjs/litestone'

const gate = new GatePlugin({
  getLevel(user, model) {
    if (!user)               return LEVELS.STRANGER       // 0
    if (user.role === 'admin') return LEVELS.ADMINISTRATOR  // 5
    return LEVELS.USER                                    // 4
  }
})

const db = await createClient({ path: './schema.lite', db: ':memory:', plugins: [gate] })
```

Levels: `STRANGER=0  VISITOR=1  READER=2  CREATOR=3  USER=4  ADMINISTRATOR=5  OWNER=6  SYSADMIN=7`
Reserved: `SYSTEM=8` (asSystem() only)  `LOCKED=9` (impassable — not even asSystem)

```
@@gate(0)          anyone can do everything
@@gate(4.4.4.6)    USER to read/create/update, OWNER to delete
@@gate(9)          nobody can do anything (model is locked)
@@gate(9.9.9.9)    same as above
```

**A schema declaring any `@@gate` auto-installs `GatePlugin`.** You cannot run
without gates — a declared-but-unenforced gate is fail-open. Installing your own
replaces the default; installing none does not disable it.

**Once a schema declares any access rule, a model with no `@@gate` and no
`@@allow`/`@@deny` is system-only on every operation**, reads included.
`@@gate(0)` says a model is public; a schema with no access rule at all is a plain ORM.

**A `@@gate` refuses and a `@@allow` filters**, which is why a wrong policy is an
empty screen rather than an error. A gate throws naming the model and the level;
a policy compiles silently into the WHERE. Any read that legitimately crosses a
policy's scope has to be `asSystem()`, or it returns nothing with a 200.

---

## `@system` and `@guarded` — two halves of one grid

Only one of the two touches reads:

| | read | write |
| --- | --- | --- |
| `@guarded` | system only | system only |
| `@system` | **anyone** | system only |

`@guarded` is a system-context lock in both directions — a non-system write
naming a guarded column is refused with an `AccessDeniedError` naming the field.
`@system` is the orthogonal sibling: the column an application writes and its
caller does not. A tracking code, a computed hint, a status the server owns.

```lite
model Order {
  id           Int     @id
  reference    String  @unique
  trackingCode String? @system     // readable by anyone, written by the app
  @@gate(2.4.4.5)
}
```

The application fills it by **naming the column on the write**, which keeps the
gate, the row policies and the audit actor — where `asSystem()` drops all three
to set one value:

```js
const app = db.$setAuth({ id: 7, role: 'member' })    // grades USER — the gate still applies
await app.order.update({ where: { id: 1 }, data: { trackingCode: 'TRK-1' }, system: ['trackingCode'] })
```

Three things follow. **Both refuse a write by name rather than dropping it**,
because the client is told the column is `readOnly` and a generated form does not
offer it — so a payload naming one is code that meant to write it. A field
`@allow(write, …)` still drops silently, and must: there the same payload is
legitimate for another caller. **`@guarded` is not a level** — it takes no
argument, and `@guarded(5)` does not parse; per-role column access is field-level
`@allow`. And a **required** `@guarded` column makes its model uncreatable below
level 8.

`@encrypted` alone is not a guard — it hides a value from a reader and stays
writable, which is what a caller submitting a secret needs. The two cannot sit on
one field, and that is the choice: `@allow(write, …)` for a column some callers
may set, `@guarded` for one only `asSystem()` touches.

---

## `@@transitions` — a state machine at the Data boundary

An enum field whose legal moves are declared, enforced on every write, and
readable by the client:

```lite
enum OrderStatus { pending  paid  shipped  refunded  cancelled }

model Order {
  id     Int         @id
  status OrderStatus @default(pending)

  @@transitions(status,
    pay:    pending         -> paid,
    ship:   paid            -> shipped,
    refund: paid            -> refunded @gate(5),
    cancel: [pending, paid] -> cancelled)

  @@gate(0)
}
```

```js
const order = await db.order.create({ data: {} })
await db.order.transition(order.id, 'pay')    // → the updated row
await db.order.transitions(order)             // → what this row may do NOW, with the gate's verdict
```

A name is optional — an unnamed clause names itself after its target state, so
`pending -> paid` is the `paid` transition. `@gate(N)` takes a level 0–9 and is
**per move**, which is the thing a gate on the model cannot say: any
USER may ship, only an ADMINISTRATOR may refund. An illegal move throws
`TransitionViolationError`; one the caller is not graded for throws
`TransitionGateError`.

It reaches the browser as **`x-transitions` on the model, keyed by field** —
never on the enum's `$def`, because only a model can carry a per-transition gate.
Sierra mirrors it as `resource.transitions(row)`, so a UI renders the buttons the
row actually has.

**`updateMany` refuses a transitions-typed column** (`BulkTransitionError`, 400):
a bulk write matches rows without reading them, so there is no from-state to
grade. Every other column stays bulk-writable in the same call. Junction's bulk
path writes one row at a time through `update()`, so `PATCH /orders?status=draft`
is graded move by move like `PATCH /orders/1`.

---

## `@version` — optimistic concurrency

```lite
model Order {
  id      Int    @id
  title   String
  version Int    @version
}
```

An `update()` must carry back the version it read, in `data`:

```js
const order = await db.order.create({ data: { title: 'Draft' } })      // version 1
await db.order.update({ where: { id: order.id }, data: { title: 'New', version: order.version } })
```

A row that moved underneath throws `VersionConflictError` (**409, `retryable`** —
re-read and re-apply); an absent version throws `VersionRequiredError` (400). A
new row is version 1 whatever the payload says, and every write bumps it.

One per model, `Int`, non-optional, never the `@id` — each refused at parse,
because a nullable version is a row that cannot be compared and that is a hole in
the guarantee. `updateMany` / `upsert` / `upsertMany` bump without requiring, and
`asSystem()` may leave the version out — a migration read nothing — but one it
states is checked, so a job that read the row first passes the version it read.

It reaches the client as `x-version`, `readOnly` in the update schema and absent
from the create schema, so Sierra's `createResource` remembers the version of
every record it read and puts it on the next patch with nobody wiring anything.

---

## `@@scope` — a named predicate a caller can ask for

The policy compiler, made explicit and opt-in:

```lite
model Task {
  id          Int       @id
  ownerId     Int
  status      String    @default("open")
  dueAt       DateTime?
  completedAt DateTime?

  @@scope(overdue, dueAt < now() && completedAt == null)
  @@scope(mine,    ownerId == auth().id)
  @@scope(active,  status == 'open' || status == 'review')
}
```

```js
db.task.findMany({ where: { $scope: 'overdue' } })
db.task.findMany({ where: { $scope: ['overdue', 'mine'] } })     // several AND
db.task.findMany({ where: { $scope: 'mine', status: 'open' } })  // composes with keys
db.task.findMany({ where: { OR: [{ $scope: 'overdue' }, { id: 5 }] } })
```

**Predicate-only** — no value, no property in the generated schema. If a UI wants
to *render* the answer it wants `@derived` instead. Several names AND; a
disjunction goes inside one scope.

The point is that **a where is the one query shape a browser can name**: a client
sends a `where` object over HTTP and cannot invoke `db.task.overdue()`. The name
is looked up in the declared table and never interpolated, and `db.$scopes(accessor)`
publishes the list — which is what `$checkWhere` validates against.

---

## `@derived` — a value SQLite computes, so you can filter and sort by it

```lite
model Task {
  id          Int       @id
  priority    Int
  dueAt       DateTime?
  completedAt DateTime?

  overdue Boolean @derived(dueAt < now() && completedAt == null)
  urgency Int     @derived(priority > 8 ? 3 : priority > 5 ? 2 : 1)
}
```

The `@@allow` expression language, compiled once at startup into the SELECT — so
unlike `@computed` (a JS function over a fetched row) it is a real column
expression and `where: { overdue: true }` and `orderBy: { urgency: 'desc' }` both
work.

**Static only.** `now()` is allowed and emits SQLite's own clock, which SQLite
fixes for the duration of a statement. `auth()` and `check()` are **refused** — a
derived field is one value for the row, and per-caller is what `@@scope` is for.
The declared type is checked against the branches at startup.

It reaches the client as `readOnly` with `x-litestone-kind: 'derived'`, plus
`x-litestone-volatile: 'clock'` when it reads the clock — a flag, never the
expression.

---

## `@@hasTemplates` — definition versus instance

A category most apps grow by hand: rows that are a *definition* sitting in the
same table as rows that are an *instance* of it.

```lite
model Workout {
  id   Int    @id
  name String
  @@hasTemplates                       // adds isTemplate Boolean @default(false)
}
```

Every read **and every write** excludes templates unless asked:

```js
db.workout.findMany()                                 // instances only
db.workout.findMany({ withTemplates: true })          // both
db.workout.findMany({ onlyTemplates: true })          // the definitions
db.workout.update({ where: { id: 1 }, data: { isTemplate: false }, withTemplates: true })
```

It is the same two flags `@@softDelete` gives, on the same methods — and
**neither is an access rule, so `asSystem()` does not lift either**; the flags are
the only way past. They part company in one place: a hard `delete` bypasses the
soft-delete filter by design (it is the purge hatch) while the template filter
still applies, because destroying rows no ordinary read returns is data loss the
caller cannot anticipate.

`@@hasTemplates(field: "isPreset")` names the column yourself.

---

## Encryption

```lite
model User {
  id     Int     @id
  ssn    String  @encrypted                        // AES-256-GCM — hidden from a non-system read
  email  String  @encrypted(deterministic: true)   // equality WHERE works; still ciphertext, so it re-keys
  pwHash String  @hashed                           // one-way — matchable, never readable
  apiKey String? @secret                           // @encrypted + @guarded + @trail(audit)

  @@gate(0)
}
```

The client takes the key: `createClient({ encryptionKey })`, 64 hex characters.

```js
await db.user.create({ data: { ssn: '123-45-6789', email: 'alice@example.com', pwHash: 'hunter2' } })
const submitted = 'hunter2'

// A stable encoding is what makes a WHERE possible — deterministic ciphertext or a digest
await db.user.findFirst({ where: { email: 'alice@example.com' } })  // ✓ the row; email reads back under asSystem()
await db.user.findFirst({ where: { pwHash: submitted } })            // ✓ the row; pwHash never reads back
await db.user.findFirst({ where: { ssn: '123-45-6789' } })           // ✗ ValidationError: random IV, nothing can match
  .catch(e => e.name)
```

Every `@encrypted` value, deterministic or not, is hidden from a non-system
read; what `deterministic` adds is the filter. `db.$rotateKey(newKey)` re-keys
every `@encrypted` and `@secret` column, and **refuses while a column it cannot
carry forward exists** — `@hashed` has no plaintext to re-key, and
`@secret(rotate: false)` opted out.

---

## Relations

`@relation` goes on the **belongsTo** side, the model holding the foreign key. The other side (`Post[]`) is inferred, and two `[]` sides make an implicit many-to-many. A relation field names the MODEL, never a table.

```lite
model User { id Int @id  name String  posts Post[] }
model Post {
  id       Int    @id
  title    String
  author   User   @relation(fields: [authorId], references: [id], onDelete: Cascade)
  authorId Int
  tags     Tag[]
}
model Tag { id Int @id  label String  posts Post[] }
```

A relation is read with `include` and written with a nested `create` / `connect`:

```js
const ann = await db.user.create({ data: { id: 1, name: 'Ann',
  posts: { create: [{ title: 'Hello', tags: { create: [{ label: 'intro' }] } }] } } })

const posts = await db.post.findMany({ include: { author: true, tags: true } })
const slim  = await db.post.findMany({ include: { author: { select: { id: true, name: true } } } })
const counted = await db.user.findMany({ include: { _count: true } })   // → _count: { posts: 1 }

await db.post.create({ data: { title: 'Again', author: { connect: { id: ann.id } } } })
```

`where` and `orderBy` reach through a belongsTo relation too. `docs/relations.md` has the rest: filtered counts, one-to-one, `@@relator`, the implicit join table, `@from` and recursive trees.

---

## Query API

The models the examples in this section read:

```lite
model Account { id Int @id  name String  users User[] }
model User    { id Int @id  email String  accountId Int  account Account @relation(fields: [accountId], references: [id])
                createdAt DateTime @default(now())  deletedAt DateTime?  @@softDelete }
model Product { id Int @id  name String  price Float  stock Int  state String @default("new") }
model Order   { id Int @id  accountId Int  amount Float  status String @default("pending")  meta Json? }
```

### Read

```js fragment
db.user.findMany({ where, orderBy, limit, offset, include, select, withDeleted, onlyDeleted })
db.user.findMany({ where, distinct: true })                    // SELECT DISTINCT
db.user.findMany({ where, window: { rn: { rowNumber: true, orderBy: { id: 'asc' } } } })
db.user.findFirst({ where, orderBy, include, select })
db.user.findUnique({ where, include, select })
db.user.findFirstOrThrow({ where })
db.user.findUniqueOrThrow({ where })
db.user.findManyAndCount({ where, orderBy, limit, offset, include, select })  // → { rows, total }
db.user.count({ where })                                                       // → number
db.user.exists({ where })                                                      // → boolean
db.user.aggregate({ where, _count, _sum, _avg, _min, _max })
db.user.groupBy({ by, where, having, orderBy, limit, offset, _count, _sum, _avg, _min, _max })
db.user.groupBy({ by, interval: { createdAt: 'month' }, fillGaps: true, _count, _sum })
db.user.query({ ...args })                                    // unified dispatcher — see below
db.user.search('words', { prefix, raw, where, limit, highlight, snippet }) // @@fts; words, not FTS5 syntax
db.user.findManyCursor({ where, limit, cursor, orderBy })              // O(log n) pagination
db.user.findMany({ where, recursive: true })                           // CTE tree (self-referential)
db.user.findMany({ where, recursive: { direction: 'ancestors', nested: true, maxDepth: 3 } })
```

### Write

```js fragment
// Single-row ops — return the full row (with include/select applied)
db.user.create({ data, include, select })          // → TRow
db.user.update({ where, data, include, select })   // → TRow | null
db.user.upsert({ where, create: {...}, update: {...} })  // → TRow
db.user.restore({ where })                         // → TRow[]

// select: false — skip RETURNING, return null. Fastest write path.
// No benefit on @@trail models (logging requires the row snapshot).
db.user.create({ data, select: false })            // → null
db.user.update({ where, data, select: false })     // → null

// Bulk ops — return { count: number } only, no row data
// Use single-row ops in a $transaction if you need the affected rows back
db.user.createMany({ data: [...] })                // → { count: number }
db.user.updateMany({ where, data })                // → { count: number }
db.user.upsertMany({ data, conflictTarget, update })  // → { count: number }
db.user.removeMany({ where })                      // → { count: number }
db.user.deleteMany({ where })                      // → { count: number }

db.user.remove({ where })      // soft delete if @@softDelete, else hard delete → TRow
db.user.delete({ where })      // always hard delete → TRow
db.user.optimizeFts()          // merge FTS5 segments — requires @@fts
```

Bulk ops intentionally skip `RETURNING` — fetching potentially thousands of rows back negates the performance reason for using a bulk op. If you need the modified rows, use a single-row op in a `$transaction` loop, or `findMany` after the bulk op.

### Two refusals worth knowing by name

**A soft-deleted row keeps its `@unique` values.** Freeing the slot would make
`@unique` false for every read that includes deleted rows — `findUnique(withDeleted)`
legitimately matching two — and would make `restore()` fail whenever a stranger
took the value first. So a write naming a value a deleted row holds is refused by
name (`SoftDeletedUniqueError`, **409**, naming the field, the value and the
holding row) rather than by SQLite. Releasing a slot is a decision the app makes:
`update({ …, withDeleted: true })` moves the value, `delete({ …, withDeleted: true })`
stops keeping the row.

**A per-call flag the model cannot satisfy is refused, and so is a method.**
`onlyDeleted` on a model with no `@@softDelete` would otherwise answer the *live*
rows — the opposite of the question, with nothing saying the flag had not
applied — and `search()` below `@@fts` would be a bare `Error` reaching a caller
as a 500. Both are `CapabilityNotDeclaredError`: **400**, naming the model and
the attribute that would make the request legal. It covers `onlyDeleted` / `onlyTemplates` on
every read and write, plus `search()`, `optimizeFts()`, `restore()` and
`transition()`.

`withDeleted` / `withTemplates` deliberately do **not** refuse: they ask to
widen, and a model that hides nothing already answers everything — which is what
generic tooling (a row browser, a *show deleted* toggle) is asking for.

### Where clause

```js fragment
{ id: 1 }
{ status: { in: ['active', 'pending'] } }
{ score: { gte: 0, lte: 100 } }
{ name: { contains: 'smith' } }
{ deletedAt: { not: null } }
{ AND: [...], OR: [...], NOT: {...} }
{ $scope: 'overdue' }                    // a @@scope the model declares
{ $raw: sql`json_extract(meta, '$.tier') = ${3}` }
```

**A bare array is not `equals`, on either kind of column.** It means *the column's
value is in this list* — `IN` for a scalar, `IN` inside `json_each` for an array
column, which is `hasSome`. **Prisma reads it as an exact match**, so a schema
ported from there filters wider than it did. The exact, ordered comparison is
`{ equals: [...] }`.

**A `where` typo throws `ValidationError`** naming the key, with a *Did you mean*
— on every flavor of client, so a service building its own filter hears it too.
Over the wire it is a 400. `db.$checkWhere(accessor, where)` is how to ask first.

### Sorting

```js fragment
// Flat field — standard
orderBy: { createdAt: 'desc' }
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }]   // multi-field

// NULLS FIRST / LAST — object form
orderBy: { deletedAt: { dir: 'asc', nulls: 'last' } }
orderBy: { priority: { dir: 'desc', nulls: 'first' } }

// The escape hatch `where` has. The fragment is the whole ORDER BY tail,
// direction included; a plain string is refused, because that is how an
// injected one would arrive. Not available with a cursor, or on groupBy.
orderBy: { $raw: sql`CASE WHEN "snoozedUntil" > ${now()} THEN 1 ELSE 0 END ASC, "dueAt" ASC` }

// Relation field orderBy — sort by a field on a belongsTo relation (LEFT JOIN)
db.post.findMany({ orderBy: { author: { name: 'asc' } } })

// Two-hop
db.user.findMany({ orderBy: { company: { country: { name: 'asc' } } } })

// Mixed flat + relation
db.post.findMany({ orderBy: [{ author: { name: 'asc' } }, { createdAt: 'desc' }] })

// Relation aggregate orderBy — sort by count/sum/avg/min/max of a hasMany or manyToMany
// Uses a correlated subquery — no row duplication, works on any table size
db.author.findMany({ orderBy: { books: { _count: 'desc' } } })
db.author.findMany({ orderBy: { books: { _sum: { price: 'desc' } } } })
db.author.findMany({ orderBy: { books: { _max: { rating: 'desc' } } } })
db.author.findMany({ orderBy: { tags:  { _count: 'asc' } } })   // manyToMany — _count only
```

Relation field orderBy (`belongsTo` only — single-row joins). Aggregate orderBy works on `hasMany` and `manyToMany`; `_sum`/`_avg`/`_min`/`_max` require `hasMany`. Both compose with `where`, `limit`, `offset`, `include`, and `select`.

### Raw SQL — `where: { $raw }`

For predicates the structured `where` builder can't express — `json_extract`, date arithmetic, `LIKE` with complex patterns, etc. Use the `sql` tagged template for safe parameter binding:

```js
import { sql } from '@frontierjs/litestone'

const state = 'clearance', minPrice = 5

// Simple
await db.product.findMany({
  where: { $raw: sql`price > CASE WHEN state = ${state} THEN ${minPrice} ELSE 100 END` }
})

// Mixed with structured where — ANDed together
await db.order.findMany({
  where: {
    status: 'active',
    $raw: sql`json_extract(meta, '$.tier') = ${3}`,
  }
})

// Composed inside AND / OR
await db.user.findMany({
  where: {
    AND: [
      { accountId: 1 },
      { $raw: sql`julianday('now') - julianday(createdAt) <= ${30}` },
    ]
  }
})

// Works everywhere where: is accepted — findMany, findFirst, count, exists, update, updateMany...
const n = await db.product.count({ where: { $raw: sql`stock < ${10}` } })
```

The `sql` tag pulls interpolated values out as params and substitutes `?` placeholders — values are never concatenated into the SQL string. Only a tag value is accepted, at any depth — a plain string is refused, because a string is how a caller's text arrives (`FJS-D613`). With nothing to interpolate it is still the tag: ``where: { $raw: sql`deletedAt IS NULL` }``. A tag interpolated into another tag is spliced in, parenthesised, with its own params kept in order (`FJS-3916`): ``sql`groupId IN (SELECT id FROM g WHERE ${settled})` ``.

### Cursor pagination

```js
const page1 = await db.user.findManyCursor({ limit: 50, orderBy: { id: 'asc' } })
// → { items: [...], nextCursor: 'eyJ...', hasMore: true }

const page2 = await db.user.findManyCursor({
  limit: 50, orderBy: { id: 'asc' }, cursor: page1.nextCursor
})
```

### Transactions

```js
await db.$transaction(async tx => {
  const acct = await tx.account.create({ data: { name: 'Acme' } })
  const user = await tx.user.create({ data: { accountId: acct.id, email: 'a@b.com' } })
  return { acct, user }
})
```

---

## onQuery — production query logging

```js
import { appendFileSync } from 'node:fs'

const db = await createClient({ path: './schema.lite', db: ':memory:',
  onQuery: (event) => {
    appendFileSync('./query.log', JSON.stringify(event) + '\n')
  }
})
```

Event shape:

```js fragment
{
  model:     'User',
  operation: 'findMany',        // all ORM operations
  database:  'main',
  actorId:   'user_abc',        // ctx.auth?.id
  system:    false,             // asSystem() ran it
  sql:       'SELECT * FROM "user" WHERE "status" = ? LIMIT ?',
  params:    ['active', 20],
  duration:  1.4,               // ms — SQLite call only
  rowCount:  17,
  args:      { where: { status: 'active' } },
}
```

Common patterns:

```js fragment
// Slow query detection
onQuery: (e) => e.duration > 100 && logger.warn('slow query', e)

// Async telemetry — never blocks the calling query
onQuery: async (e) => { await telemetry.track(e) }

// Per-actor audit
onQuery: (e) => e.actorId && audit.log(e)
```

Use `db.$tapQuery(fn)` for temporary one-shot captures (Litestone Studio's REPL, tests):

```js
const log = []
const stop = db.$tapQuery(e => log.push(e))
await db.user.findMany()
stop()
// log contains all queries that fired
```

---

## The audit trail — `@@trail` records a write, `$audit` records an event

`@@trail(audit)` covers **writes**, which means the events an application most
wants are exactly the ones it cannot see. A sign-in is not a write to `User`, and
a *failed* one is not a write at all — so nothing the trail can observe names the
actor or the attempt.

`db.$audit()` is the one way to put a row there by hand:

```lite
database audit { path "./audit/"; driver trail }

model User {
  id       Int    @id
  email    String
  fullName String @computed
  @@trail(audit)
}
```

```js
const user = { id: 1 }

await db.$audit({
  operation: 'login.failed',
  model:     'User',
  records:   [user.id],
  actorId:   user.id,          // defaults to this client's principal; a system context has none
  meta:      { reason: 'bad-password' },
})
```

**It awaits and throws**, where `@@trail` is fire-and-forget — there the record is a
side effect of a write that already succeeded and must not fail it; here it *is*
the point. **Inside a `$transaction` it files at call time and survives a rollback**,
where a write's line waits for the commit: an event is true whether or not the
transaction around it does, and a failed attempt inside a refused transaction is
the row this call exists for (`FJS-D1740`). An unknown key is refused by name, a stated `actorId` beats `onLog`'s,
and `meta` is **not redacted** — it is yours, so do not put a secret in it. On
every flavor of client.

**Protected fields are redacted in the trail.** Any `@encrypted` / `@guarded` /
`@secret` value logs as `[redacted]` in both the field entry and the
`before`/`after` images — the record says *that* the field was written, never
what it held. That is what makes `@secret`'s expansion safe: it implies
`@trail(<first trail db>)`, so declaring a trail database alone starts logging
every secret field, and without redaction that writes plaintext beside a correctly
encrypted row. `null` is preserved rather than redacted.

**The trail defers one event-loop tick.** `fireLog()` schedules with
`setImmediate` and the jsonl driver appends synchronously, so a read in the same
tick sees 0 rows and the `.jsonl` may not exist yet. Yield once; do not wait —
there is no timed buffer and no flush on exit.

---

## Write events — `$tapEvents`

Every write announces, and the event says whether it can name its row:

```js
const stop = db.$tapEvents(e => {
  e.scope === 'row'          // one row — `result` is it, or null where select: false
  e.scope === 'collection'   // `count` rows matching `where`, from a statement that never built them
})
```

**The scope is stated, never read off `result`** — those are two facts, and
`result: null` means both *this write skipped the RETURNING* and *this was a bulk
statement*. Treating it as "no rows" is what silently dropped every
`select: false` write a layer up. A write matching **no** rows announces nothing:
a count of zero sending every open tab back to the server is worse than silence.

**`announce` is the dial on a bulk write, and it is per call:**

```js fragment
db.user.updateMany({ where, data })                      // 'collection' — one event, O(1)
db.user.updateMany({ where, data, announce: 'rows' })    // one event per row, off RETURNING
db.user.updateMany({ where, data, announce: 'none' })
createClient({ …, announce: 'rows' })                    // the floor; a call beats it
```

Not decidable by size — the count is unknowable before the write without a second
query — so it is declared and never guessed, and it is the *call* rather than the
model, since one model carries both a three-row cancel and a two-million-row purge.
An unknown value is refused by name before the statement runs.

Junction taps this and routes it into the same real-time fan-out a service write
uses, so a write that came through no service still reaches every open tab.

---

## Is this a valid filter? — `$checkWhere` / `$checkOrderBy`

A layer above needs to grade a caller-supplied `where` or `orderBy` *before*
running it, and re-deriving the rules would be a second answer to one question:

```js
db.$checkWhere('user', { emial: 'x' })
// → [{ key: 'emial', reason: 'unknown', suggestion: 'email', allowed: ['email', 'id'], message: '…' }]

db.$checkOrderBy('user', { fullName: 'asc' })
// → [{ key: 'fullName', reason: 'computed', suggestion: null, sortable: ['email', 'id'], message: '…' }]
```

`reason` separates *no such field* from **`computed`** (a JS function over a
fetched row — SQLite can neither sort nor paginate by one) from **`opaque`**: an
array, a `Json` document, a `File` or an encrypted column, whose stored TEXT is a
serialization rather than the value, so ordering by it is always plausible and
never what was asked. A `@from` and a `@derived` field both sort fine.

An unknown accessor answers `[]` — *I cannot judge this* is not *this is wrong*.
Both live on **every** flavor of client: filterability is a fact about the
schema, and auth has no bearing on it.

Both ANSWER rather than throw — an empty list is a clean filter. The query
itself is where **a bad key throws**, in `where` and `orderBy` alike, with a
*Did you mean* — a wrong filter answers the wrong rows and a wrong sort the right
rows in the wrong order, and neither is visible in the result.

---

## Migrations

```js
import { autoMigrate, parseFile } from '@frontierjs/litestone'
import { create, apply, status, verify } from '@frontierjs/litestone/migrations'
import { openDatabase } from '@frontierjs/litestone/engine'

const parseResult = parseFile('./schema.lite')

// Dev — apply changes directly, no files (like prisma db push)
autoMigrate(db, parseResult)

// Production — file-based, over the raw handle of ONE database
const raw = openDatabase('./app.db')
create(raw, parseResult, 'add-users', './migrations')  // generate SQL file
await apply(raw, './migrations')                       // apply pending
status(raw, './migrations')                            // show applied/pending
verify(raw, parseResult, './migrations')               // check live vs schema
```

`autoMigrate` takes the client and walks every database it holds; the four
file-based calls take a raw SQLite handle, one database at a time.

```bash
litestone migrate create [label]   # generate migration SQL file
litestone migrate apply            # apply pending migrations
litestone migrate status           # show applied / pending / modified
litestone migrate verify           # check live db matches schema
litestone migrate dry-run [label]  # preview SQL, no file written
```

---

## Schema functions

Reusable named SQL expressions — define once, use on any model:

```lite
function slug(text: String): String {
  @@expr("lower(trim(replace({text}, ' ', '-')))")
}

function fullName(first: String, last: String): String {
  @@expr("COALESCE({first}, '') || ' ' || COALESCE({last}, '')")
}

model User {
  id          Int     @id
  firstName   String?
  lastName    String?
  displayName String  @fullName(firstName, lastName)  // STORED generated column
}

model Post {
  id    Int     @id
  title String
  slug  String  @slug(title)   // same function, different model
}
```

Generated columns are `STORED` and indexable:

```js
await db.post.findMany({ where: { slug: 'hello-world' } })
await db.user.findMany({ orderBy: { displayName: 'asc' } })
```

---

## @sequence — per-scope auto-increment

```lite
model Quote {
  id          Int @id
  accountId   Int
  quoteNumber Int @sequence(scope: accountId)
}
```

Each account gets its own counter starting at 1:

```js
const q = await db.quote.create({ data: { accountId: 5 } })
// q.quoteNumber → 1  (first quote for account 5)
String(q.quoteNumber).padStart(4, '0')  // → '0001'
```

---

## @from — derived relation fields

Computed aggregates and lookups from related models — evaluated at query time, not stored.

```lite
model Account {
  id         Int      @id
  name       String
  orders     Order[]                                   // the relation @from reads
  orderCount Int      @from(Order, count: true)
  revenue    Float    @from(Order, sum: amount)
  biggest    Float    @from(Order, max: amount)
  lastOrder  Order?   @from(Order, last: true)         // the whole row, not a column
  hasBig     Boolean  @from(Order, exists: true, where: amount > 100)
}

model Order {
  id        Int      @id
  accountId Int
  account   Account  @relation(fields: [accountId], references: [id])
  amount    Float
  status    String   @default("paid")
  createdAt DateTime @default(now())
}
```

**The first argument is the target model name, PascalCase** — `@from(Order, …)`, not the relation
field name; `@from(orders, …)` is *"unknown model 'orders'"*. **`first:`/`last:` return the whole
related row**, so the field is typed as that model (`Order?`), not as one of its columns.

Exactly one operation is required: `count: true` (field must be `Int`), `sum: field` /
`max: field` / `min: field`, `first: true` / `last: true` (field typed as the target model),
`exists: true` (field must be `Boolean`). Options are `where: "sql"` and `orderBy: field`
(what `first`/`last` order by — defaults to `id`).

Derived fields are read-only and appear in query results automatically. `sum` coalesces to `0`
on an empty set while `max`/`min` stay `null`. The declared relation is what `@from` joins on,
and a schema without one is a parse error naming the relation you need.

See `docs/relations.md` for the full table.

---

## aggregate() and groupBy()

```js
// Simple aggregate
const stats = await db.order.aggregate({
  where:  { status: 'completed' },
  _count: true,
  _sum:   { amount: true },
  _avg:   { amount: true },
  _min:   { amount: true },
  _max:   { amount: true },
})
// → { _count: 142, _sum: { amount: 98432.50 }, _avg: { amount: 693.19 }, ... }

// COUNT(DISTINCT field)
db.order.aggregate({ _count: { distinct: 'accountId' } })

// string_agg / group_concat
db.order.aggregate({
  _stringAgg: { field: 'status', separator: ', ', orderBy: 'status' }
})
// → { _stringAgg: { status: 'paid, pending, refund' } }

// Named aggregates — any _-prefixed key with an agg fn spec
// Supports FILTER (WHERE ...) for single-pass pivot queries
const pivot = await db.order.aggregate({
  _count:       true,
  _countPaid:   { count: true,   filter: sql`status = 'paid'` },
  _countRefund: { count: true,   filter: sql`status = 'refund'` },
  _sumPaid:     { sum: 'amount', filter: sql`status = 'paid'` },
  _avgPaid:     { avg: 'amount', filter: sql`status = 'paid'` },
})
// → { _count: 100, _countPaid: 72, _countRefund: 8, _sumPaid: 3200, _avgPaid: 44.4 }

// Group by field
const byStatus = await db.order.groupBy({
  by:      ['status'],
  _count:  true,
  _sum:    { amount: true },
  having:  { _count: { gt: 5 } },
  orderBy: { _count: 'desc' },
})

// Per-group filtered stats
await db.order.groupBy({
  by:           ['accountId'],
  _count:       true,
  _countPaid:   { count: true,   filter: sql`status = 'paid'` },
  _sumPaid:     { sum: 'amount', filter: sql`status = 'paid'` },
})

// Time-series bucketing with gap fill
const monthly = await db.order.groupBy({
  by:       ['createdAt'],
  interval: { createdAt: 'month' },   // year | quarter | month | week | day | hour
  where:    { createdAt: { gte: '2024-01-01', lte: '2024-12-31' } },
  fillGaps: true,   // default true when interval present — CTE-based, no missing buckets
  _count:   true,
  _sum:     { amount: true },
})
// → [{ createdAt: '2024-01', _count: 18, _sum: { amount: 4200 } }, ...]

// findManyAndCount — single query, total for pagination
const { rows, total } = await db.order.findManyAndCount({
  where: { status: 'paid' },
  limit: 20, offset: 40,
})
```

---

## Window functions

Window functions add computed columns to each row based on a set of surrounding rows — rankings, running totals, moving averages, period comparisons. Pass a `window` object to `findMany`:

```js
db.order.findMany({
  where:   { accountId: 1 },
  orderBy: { id: 'asc' },
  window:  {
    // Positional — row number, rank, dense rank
    rn:        { rowNumber: true, partitionBy: 'accountId', orderBy: { id: 'asc' } },
    rank:      { rank: true,      partitionBy: 'accountId', orderBy: { amount: 'desc' } },
    denseRank: { denseRank: true,                           orderBy: { amount: 'desc' } },

    // Adjacent rows — previous / next value
    prev: { lag:  'amount', offset: 1, default: 0, orderBy: { id: 'asc' } },
    next: { lead: 'amount', offset: 1, default: 0, orderBy: { id: 'asc' } },

    // Partition boundary values
    first: { firstValue: 'amount', partitionBy: 'accountId', orderBy: { id: 'asc' }, rows: [null, null] },
    last:  { lastValue:  'amount', partitionBy: 'accountId', orderBy: { id: 'asc' }, rows: [null, null] },

    // Running aggregates
    runningTotal: { sum:   'amount', orderBy: { id: 'asc' } },
    runningCount: { count: true,     orderBy: { id: 'asc' } },

    // Rolling window — 7-row moving average
    ma7: { avg: 'amount', orderBy: { createdAt: 'asc' }, rows: [-6, 0] },

    // Conditional aggregate window — FILTER (WHERE ...)
    paidRunning: { sum: 'amount', filter: sql`status = 'paid'`, orderBy: { id: 'asc' } },
  }
})
// → rows with all normal fields + computed window columns mixed in:
// [{ id: 1, amount: 10, rn: 1, rank: 3, runningTotal: 10, prev: 0, ... }, ...]
```

All window functions support `partitionBy` (single field or array), `orderBy` (same syntax as query-level, including NULLS FIRST/LAST), and `rows`/`range` frame specs.

Frame spec: `rows: [-6, 0]` → `ROWS BETWEEN 6 PRECEDING AND CURRENT ROW`. Use `null` for unbounded: `rows: [null, null]` → `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`.

Available functions: `rowNumber`, `rank`, `denseRank`, `cumeDist`, `percentRank`, `lag`, `lead`, `firstValue`, `lastValue`, `nthValue`, `ntile`, `sum`, `avg`, `min`, `max`, `count`.

---

## query() — unified dispatcher

Routes a single args object to `findMany`, `groupBy`, or `aggregate` based on its shape. Designed for API layers that receive query descriptors from request parameters:

```js fragment
// One handler, all query types
app.get('/orders', async (req) => {
  return db.order.query(req.query)
})
```

```js
// → findMany (no aggregate keys, no by)
db.order.query({ where: { status: 'paid' }, orderBy: { id: 'asc' }, limit: 20 })

// → aggregate (has _count/_sum/etc, no by)
db.order.query({ _count: true, _sum: { amount: true }, where: { accountId: 1 } })

// → groupBy (has by)
db.order.query({ by: ['status'], _count: true, where: { accountId: 1 } })

// → findMany + window
db.order.query({ window: { rn: { rowNumber: true, orderBy: { id: 'asc' } } } })

// → aggregate (named agg with FILTER)
db.order.query({ _countPaid: { count: true, filter: sql`status = 'paid'` } })
```

Routing rules — checked in order: `by` present → `groupBy`; `_count`/`_sum`/`_avg`/`_min`/`_max`/`_stringAgg` or named agg present → `aggregate`; everything else → `findMany`. All standard args (`where`, `orderBy`, `limit`, `select`, `include`, `window`, `distinct`, `$raw`, etc.) pass through unchanged.

### Multi-model — `db.query(spec)`

`db.query(spec)` runs many per-model queries in one snapshot transaction and returns a named-result object. Each entry routes through the per-model dispatcher above:

```js
// Page-load fan-out — keys match model accessors, all run in one snapshot
const { account, order, revenue } = await db.query({
  account: { where: { name: 'Acme' } },                          // → findMany
  order:   { _count: true, _sum: { amount: true } },             // → aggregate
  revenue: { model: 'order', by: ['status'], _count: true },     // → groupBy (aliased)
})

// Same model, multiple queries — use `model:` to alias
const { paid, pending } = await db.query({
  paid:    { model: 'order', where: { status: 'paid' } },
  pending: { model: 'order', where: { status: 'pending' } },
})

// Auth scoping composes — each entry inherits the proxy's auth
const req  = { user: { id: 1 }, body: { order: { _count: true } } }
const data = await db.$setAuth(req.user).query(req.body)

// Or trusted server work bypassing policies
const all  = await db.asSystem().query({ order: { _count: true }, account: { _count: true } })
```

The spec is JSON-shaped (no methods, no promises — just args), so the simplest possible read API is one HTTP endpoint:

```js fragment
app.post('/query', async (req, res) => {
  res.json(await db.$setAuth(req.user).query(req.body))
})
```

Whole-batch failure: any throw rolls back the transaction. For per-entry tolerance, call `db.<model>.query()` per model and use `Promise.allSettled`.

---

## Scopes

Reusable named query fragments registered per model. A scope is a plain object shaped like findMany args; the `where` may be a function for dynamic filtering.

```lite
model Customer {
  id      Int    @id
  status  String @default("active")
  tier    String @default("basic")
  ownerId Int?
}
```

```js
// db/scopes/customer.js — a module of named fragments, keyed by MODEL name on the client
const CustomerScopes = {
  active:  { where: { status: 'active' } },
  premium: { where: { tier: 'premium' } },
  mine:    { where: (ctx) => ({ ownerId: ctx.auth?.id }) },
}

const db = await createClient({
  path:   './schema.lite',
  db:     ':memory:',
  scopes: { Customer: CustomerScopes },
})

// Callable function-with-properties on the accessor: the default call is findMany,
// and every read method is there under the scope. Scopes chain.
await db.customer.active()                          // findMany under one scope
await db.customer.active.count()                     // count under scope
await db.customer.active.premium.findMany()          // chained
await db.$setAuth({ id: 1 }).customer.mine.aggregate({ _count: true })
```

**Merge rules:** all `where` clauses (scope + caller) AND-merge; everything else is last-write-wins, with caller args overriding all scope args. Soft-delete filtering still applies.

**Conflict guard:** scope names cannot shadow built-in methods, relation fields on the same model, or start with `$`/`_`. Violations throw at `createClient` time.

**Scopes are not policies.** Scopes are opt-in — you have to call them. If a where clause must apply for security, write it as `@@allow`/`@@deny`, not as a scope.

**Parameterized scopes are not supported.** Write a function that returns a `where` clause and pass it as a caller override. See [docs/querying.md](./docs/querying.md#scopes) for full details.

---

## Recursive tree queries

Self-referential models (a field referencing the same model) automatically support CTE-based tree traversal:

```lite
model Category {
  id       Int     @id
  name     String
  parent   Category? @relation(fields: [parentId], references: [id])
  parentId Int?
  children Category[]
}

model Employee {
  id        Int       @id
  name      String
  managerId Int?
  manager   Employee? @relation("reports", fields: [managerId], references: [id])
  reports   Employee[] @relation("reports")
  mentorId  Int?
  mentor    Employee? @relation("mentoring", fields: [mentorId], references: [id])
  mentees   Employee[] @relation("mentoring")
}
```

```js
// All descendants of node 5
const tree = await db.category.findMany({
  where:     { id: 5 },
  recursive: true,             // direction: 'descendants' (default)
})

// All ancestors (path to root)
const breadcrumb = await db.category.findMany({
  where:     { id: 42 },
  recursive: { direction: 'ancestors' },
})

// Nested tree structure (children array on each node)
const nested = await db.category.findMany({
  where:     { parentId: null },
  recursive: { direction: 'descendants', nested: true, maxDepth: 3 },
})

// Multiple self-relations — disambiguate with via: the parent-side field (or its FK)
const reports = await db.employee.findMany({
  where:     { id: 1 },
  recursive: { direction: 'descendants', via: 'manager' },
})
```

---

## Data changes are not migrations

`migrations/` holds `.sql` only; a `.js` file there is refused by `migrate create`, `check` and `apply` with a nonzero exit (`FJS-D518`). A backfill is an app script chained after `migrate apply`, idempotent by the rows it expects — [docs/migrations.md](./docs/migrations.md#data-changes-are-not-migrations).

---

## Computed fields

```js
// computed.js
export default {
  User: {
    fullName: row => [row.firstName, row.lastName].filter(Boolean).join(' '),
    isActive: row => !row.deletedAt,
  }
}
```

A content check written in code is a `$validate` entry in the same file, bound to the field it grades by `@validate` — [docs/schema.md § A check written in code](./docs/schema.md#a-check-written-in-code-validate-validate).

```lite
model User {
  id        Int       @id
  firstName String?
  lastName  String?
  email     String
  deletedAt DateTime?
  fullName  String    @computed
  isActive  Boolean   @computed
}
```

---

## File storage — FileStorage plugin

```js
import { FileStorage, fileUrl, fileUrls, useStorage } from '@frontierjs/litestone/storage'

const db = await createClient({ path: './schema.lite', db: ':memory:',
  plugins: [FileStorage({
    provider:   'r2',
    bucket:     'my-app',
    endpoint:   process.env.S3_ENDPOINT,
    accessKeyId:     process.env.S3_KEY,
    secretAccessKey: process.env.S3_SECRET,
  })]
})
```

```lite
model User {
  id      Int @id
  avatar  File?              // single file — upload on create/update, delete on row delete
  resume  File?  @keepVersions  // keep old S3 object on update
  photos  File[]             // multiple files — array of refs stored as JSON
  docs    File[] @accept("application/pdf,application/msword")  // type-validated
  banner  File?  @accept("image/*")   // images only
}
```

```js fragment
// Single file
const user = await db.user.update({ where: { id: 1 }, data: { avatar: file } })
fileUrl(user.avatar)                              // → 'https://cdn.example.com/...'

// Multiple files
const user2 = await db.user.update({ where: { id: 1 }, data: { photos: [file1, file2] } })
fileUrls(user2.photos)                            // → ['https://...', 'https://...']

// Storage utilities
const storage = useStorage(config)
await storage.sign(user.avatar, { expiresIn: 3600 })  // presigned URL
await storage.download(user.avatar)              // → Buffer
await storage.stream(user.avatar)                // → ReadableStream, for an object too large to hold whole
storage.path(user.avatar)                        // → file path under provider 'local', null otherwise
```

`@accept` validates MIME type before upload — supports wildcards (`image/*`, `video/*`) and comma-separated lists. Throws `ValidationError` with a clear message if the type doesn't match.

---

## ExternalRefPlugin — custom external-backed fields

`FileStorage` is built on `ExternalRefPlugin`, a base class for any field whose value is stored outside SQLite. Use it to build plugins where a field's raw value is a stored reference object and queries return a resolved value.

```js
import { ExternalRefPlugin } from '@frontierjs/litestone'

class MyPlugin extends ExternalRefPlugin {
  fieldType = 'MyType'   // matches the scalar type name used in .lite schema

  // Is this an un-serialized raw value (vs a stored ref object)?
  _isRawValue(v) { return v instanceof Buffer }

  // Store the raw value externally, return a ref object for SQLite
  async serialize(value, { field, model, id, ctx }) {
    const key = `${model}/${id}/${field}`
    await myStorage.put(key, value)
    return { key, size: value.length }
  }

  // Resolve a stored ref → the value returned to the caller
  async resolve(ref, { field, model, ctx }) {
    return myStorage.getUrl(ref.key)
  }

  // Clean up external storage when the row/field is deleted
  async cleanup(ref, { field, model, ctx }) {
    await myStorage.delete(ref.key)
  }

  // Optional: cache key for resolved values (null = no cache)
  cacheKey(ref) { return ref.key }
}
```

Set `autoResolve: true` (the default on `FileStorage`) to have `resolve()` called automatically on every read. Opt out per-field with `select: { field: { resolve: false } }` to get the raw ref object instead.

---

## Testing utilities

**Litestone is the Testing realm's Data half.** `@frontierjs/litestone/testing`
is the environment a Data-realm test runs in; `@frontierjs/testing` sits above
Junction and adds the API half, because Litestone may not import Junction.

```js
import {
  createTestEnv, makeTestClient,
  Factory, defineFactory, Seeder, loadFixture,
  factoryFrom, generateFactory, generateGateMatrix, generateValidationCases,
  deriveAccess, gateLadder, schemaMutants, mutationScore,
  snapshot, restore, truncate, reset, readOnly,
} from '@frontierjs/litestone/testing'
```

The schema the examples below run against:

```lite
model Account { id Int @id  name String  leads Lead[]  users User[]  @@gate(0) }
model Lead    { id Int @id  email String @email  score Int @gte(0) @lte(100)  loadId String?
                accountId Int  account Account @relation(fields: [accountId], references: [id])  @@gate(0) }
model User    { id Int @id  email String @email  role String @default("member")
                accountId Int  account Account @relation(fields: [accountId], references: [id])  posts Post[]  @@gate(0) }
model Post    { id Int @id  title String @length(3, 80)  authorId Int  author User @relation(fields: [authorId], references: [id])
                tags Tag[]  @@gate(1.3.4.6) }
model Tag     { id Int @id  name String  posts Post[]  @@gate(0) }
```

### createTestEnv — the environment

A migrated database, a client, factories and a principal. Tables arrive as a
**file copy** from a template migrated once per schema per process, which is
what makes one environment per test affordable.

```js
import { createTestEnv } from '@frontierjs/litestone/testing'

const env = await createTestEnv({
  schema:        './schema.lite',  // the text, or a path to it — imports spliced in
  autoFactories: true,             // env.factories.<accessor> for every sqlite model
})
const user = { id: 1, role: 'member' }

env.actingAs(user)      // the app's own getLevel — anything about behavior
await env.atLevel(4)    // a SYNTHETIC standing — the gate grid only
env.seal()
env.reset()
env.close()
```

`migrations: './migrations'` replays the committed files instead of generating
DDL, so the tests run against the database a deploy produces; `plugins` and every
other `createClient` option pass through.

**Arrange / act / assert as three clients rather than three comments.** `setup`
is the arrange every scenario shares — run once, restored by each `phases()` call:

```js
import { expect }        from 'bun:test'
import { createTestEnv } from '@frontierjs/litestone/testing'

const env       = await createTestEnv({ schema: './schema.lite', autoFactories: true })
const developer = { id: 1, role: 'developer' }

const fx = await env.setup(({ factories }) => factories.account.createOne())
const t  = env.phases({ as: developer })

const lead = await t.arrange(({ factories }) => factories.lead.createOne())
await t.act(as => as.lead.remove({ where: { id: lead.id } }))
await t.assert(read => expect(read.lead.count()).resolves.toBe(0))
```

### The five executed checks

Not assertions you write — the declared surface, **run**:

```js
import { createTestEnv } from '@frontierjs/litestone/testing'
const env = await createTestEnv({ schema: './schema.lite', autoFactories: true })

await env.verifyGateLadder()      // every gated model × every level × all four ops
await env.verifyReadLadder()      // the read column alone — no fixtures needed
await env.verifyConstraints()     // every declared rule, against a real write
await env.verifyFieldProtection() // @guarded/@encrypted/@secret, actually read back
await env.verifyRowPolicies()     // @@allow/@@deny — rows on BOTH sides
```

Three of them exist because the obvious test passes against a broken
implementation. **A UNIQUE collision is indistinguishable from a validator
working** — both are a throw on a write that should have been refused — so
`verifyConstraints` checks for `ValidationError` *by name* and reports anything
else as an error rather than a pass. **Rows on one side of a predicate prove
nothing**: a policy that admits everything and a policy that is not applied at
all are the same observation, so `verifyRowPolicies` needs both sides, and it
grades the compiled SQL against Litestone's own JS evaluator — a real oracle
rather than a restatement.

### Mutation — is the suite worth anything?

Mutate the schema, run the **original's** checks against the mutant. A mutant
nothing notices is a hole in the suite, and it names itself:

```js
import { createTestEnv, mutationScore } from '@frontierjs/litestone/testing'

const schema = await Bun.file('./schema.lite').text()
const { score, survived } = await mutationScore({
  schema, build: (text) => createTestEnv({ schema: text }),
})
```

`litestone mutate` is the CLI. **Only a verdict disagreement kills a mutant** —
counting a harness error as a kill reads as a high score while mutations go
unnoticed. Mutation is code-only and quote-aware: an attribute named inside a
doc comment is prose, and editing it produces a mutant identical in behavior
that survives everything.

### makeTestClient

```js
import { makeTestClient, Factory } from '@frontierjs/litestone/testing'

class UserFactory extends Factory {
  model = 'User'
  definition(seq, rng) { return { email: `user${seq}@test.com`, role: 'member', accountId: 1 } }
}

const schemaText = await Bun.file('./schema.lite').text()
const { db, factories } = await makeTestClient(schemaText, {
  seed:         42,               // deterministic RNG for all factories
  autoFactories: true,            // auto-generate factories for all sqlite models
  factories: { user: UserFactory },  // explicit factories (override auto-generated)
  data: async (db) => {          // seeder fn runs after tables created
    await db.account.create({ data: { id: 1, name: 'Test Co' } })
  },
})
```

### Factory

```js
import { makeTestClient, Factory } from '@frontierjs/litestone/testing'

class UserFactory extends Factory {
  model = 'User'

  states = {
    admin:  { role: 'admin' },
    viewer: { role: 'viewer' },
  }

  definition(seq, rng) {
    return { email: `user${seq}@test.com`, role: 'member', accountId: 1 }
  }
}

const schemaText = await Bun.file('./schema.lite').text()
const { db, factories } = await makeTestClient(schemaText, {
  autoFactories: true,
  factories:     { user: UserFactory },
  data:          async (db) => { await db.account.create({ data: { id: 1, name: 'Test Co' } }) },
})
const users = factories.user
const posts = factories.post.asSystem()          // Post declares @@gate

// Usage
const user    = await users.admin().createOne()
const users5  = await users.createMany(5)
const seeded  = users.seed(42).buildMany(10)   // deterministic

// withRelation — auto-create parent
const post = await posts.withRelation('author', users).createOne()
// post.authorId = (auto-created user).id, post.author = the created user

// for() — use existing parent
const post2 = await posts.for('author', user).createOne()

// withParents() — auto-create EVERY required parent, recursively, from the schema.
// The only way to seed a uuid-keyed model: a String FK has no fallback value.
const post3 = await posts.withParents().createOne()

// has() — hasMany children, FK pointed back at the parent
const author = await users.asSystem().has('posts', 3).createOne()
author.posts   // → 3 posts, each with authorId = author.id

// attach() — implicit many-to-many
await posts.withParents().attach('tags', 3).createOne()

// asSystem() / actingAs() — a schema with @@gate refuses an anonymous factory.
// The client propagates through the whole wired graph.
await factories.post.asSystem().withParents().createOne()

// create()/build() overload on the FIRST argument: a number is a count,
// anything else is overrides.
await users.create()                     // → 1 row
await users.create({ role: 'admin' })    // → 1 row with overrides
await users.create(5)                    // → 5 rows
await users.create(5, { role: 'admin' }) // → 5 rows with overrides
```

`model` is the schema's model name — PascalCase singular. Every chain method returns
a **clone**, so `f.seed(42)` does not mutate `f`.

### defineFactory — no subclass

```js
import { defineFactory, makeTestClient } from '@frontierjs/litestone/testing'

export const UserFactory = defineFactory({
  model:      'User',
  definition: (seq, rng) => ({ email: `u${seq}@x.com`, role: 'member', accountId: 1 }),
  states:     { admin: { role: 'admin' } },
})
// returns a CLASS — registers like any other:
const schemaText = await Bun.file('./schema.lite').text()
await makeTestClient(schemaText, { factories: { user: UserFactory } })
```

`fli make:factory User` scaffolds one into `db/factories/`.

### snapshot / restore — seed once, reset between tests

```js
import { snapshot, restore } from '@frontierjs/litestone/testing'

await db.account.create({ data: { name: 'Acme' } })   // the seed every test shares
const clean = snapshot(db)
restore(db, clean)                                     // in beforeEach
```

Raw rows through the write connection: `@encrypted` keeps its exact ciphertext, no
gate/hook/audit fires, FTS shadow tables are skipped. Not a transaction.

### Loading rows from outside — `loadRows`

Data somebody else wrote, read against the schema row by row. Every text cell is
parsed as its column's type (`@frontierjs/toolbelt/cells`): an enum member exactly,
a `DateTime` as ISO 8601 with a zone, `@money` and `@scale` by their digits at the
column's scale, and a quoted or unquoted `0123` in a `String` column as `'0123'`.
A cell that is not its type is a **reject** and the load goes on.

```js
import { loadRows } from '@frontierjs/litestone'

await db.account.create({ data: { id: 1, name: 'Acme' } })
const csvText = 'id,email,score,accountId\n1,a@example.com,50,1\n2,b@example.com,high,1\n'

const { loaded, rejects } = await loadRows(db.asSystem(), 'Lead', csvText, {
  key:   'id',                                  // a repeat in the file is a reject
  mode:  'replace',                             // or 'insert' (default), 'upsert'
  stamp: { loadId: 'run-7' },                   // what every row carries
})
// rejects: [{ row: 1, line: 3, key: '2', field: 'score', reason: 'not a whole number' }]
```

- `loaded + rejects.length` is always the number of input rows.
- **A reason never quotes the cell**: the text may be what the column encrypts.
- A header naming no column, or a required column with no default that the file
  lacks, **throws** before any row: every row would be rejected for it. Under
  `mode: 'upsert'` it does not: a row whose key is stored keeps the value the
  file lacks or leaves blank, and a row whose key is new is a reject naming it.
- A non-string value (a record from an API) goes to the ORM as it is.
- The source is read as the load writes, a `batch` at a time: memory is a batch
  and the keys seen, not the file. Records may be an array or any (async)
  iterable, so a REST source's pages load as they arrive.
- `dryRun: true` runs the whole load and rolls it back.
- `1,234.50` is a reject, not a number: in `de-DE` that text is 1.2345.
- `overflow: '_extra'` names an optional `Json?` column that keeps, per row,
  every header or key naming no column, as it arrived. Without it the schema is
  frozen and such a name throws before any row.

### Fixtures — authored reference data

```js
import { loadFixture } from '@frontierjs/litestone'

await Bun.write('./fixtures/accounts.json', JSON.stringify([{ id: 1, name: 'Acme' }, { id: 2, name: 'Globex' }]))
await Bun.write('./fixtures/leads.csv', 'id,email,score,accountId\n1,a@example.com,50,1\n2,b@example.com,70,2\n')

await loadFixture(db, 'Account', './fixtures/accounts.json')
await loadFixture(db, 'Lead',    './fixtures/leads.csv', { mode: 'upsert', key: 'id' })
```

`loadRows` with one difference: a fixture is authored, so any reject throws, naming the rows.

### Seeder ordering

```js
import { Seeder } from '@frontierjs/litestone/testing'

class AccountSeeder extends Seeder { async run(db) { await db.account.create({ data: { id: 1, name: 'Acme' } }) } }
class TagSeeder     extends Seeder { async run(db) { await db.tag.create({ data: { name: 'red' } }) } }

class LeadSeeder extends Seeder {
  static dependsOn = [AccountSeeder, TagSeeder]       // run first, once each
  async run(db) { await db.lead.create({ data: { email: 'a@example.com', score: 50, accountId: 1 } }) }
}
```

### factoryFrom — zero-config

```js
import { factoryFrom } from '@frontierjs/litestone/testing'

const { schema } = parse(await Bun.file('./schema.lite').text())
const accounts   = factoryFrom(schema, 'Account', db)
const acme       = await accounts.state({ name: 'Acme' }).createOne()
```

### generateFactory — schema-derived definition

```js
import { generateFactory } from '@frontierjs/litestone/testing'

const { schema } = parse(await Bun.file('./schema.lite').text())
const defFn = generateFactory(schema, 'Lead')
// Returns a definition(seq, rng) function that generates valid data from field types + constraints
// @email → an address, @gte(0) @lte(100) → a number in range, String? → null, etc.
```

### generateGateMatrix — permission test cases

```js
import { generateGateMatrix } from '@frontierjs/litestone/testing'

const { schema } = parse(await Bun.file('./schema.lite').text())
const matrix = generateGateMatrix(schema, 'Post')
// → [{ op: 'read', required: 1, level: 1, label: 'VISITOR', expect: 'allow' }, ...]

for (const { op, level, label, expect: expected } of matrix)
  console.log(`${op} as ${label} (${level}) → ${expected}`)   // one test() per row in a suite
```

### generateValidationCases — constraint boundary data

```js
import { expect }                  from 'bun:test'
import { generateValidationCases } from '@frontierjs/litestone/testing'

const { schema } = parse(await Bun.file('./schema.lite').text())
const { valid, invalid, boundary } = generateValidationCases(schema, 'Lead')

// valid    — a complete valid record (correct by construction)
// invalid  — one failing case per constraint: { field, value, rule, expect: 'fail', message }
// boundary — boundary values that should pass: { field, value, rule, expect: 'pass' }

await db.account.create({ data: { id: 1, name: 'Acme' } })
await db.lead.create({ data: { ...valid, accountId: 1 } })        // valid data passes

for (const c of invalid)                                          // one test() per case in a suite
  await expect(db.lead.create({ data: { ...valid, accountId: 1, [c.field]: c.value } }))
    .rejects.toThrow(c.message)
```

### Teardown

```js
import { makeTestClient, truncate, reset } from '@frontierjs/litestone/testing'

const { db, factories } = await makeTestClient(await Bun.file('./schema.lite').text(), { autoFactories: true })

await truncate(db, 'Post')         // hard-delete all rows in one table
await reset(db)                    // hard-delete all tables in FK-safe order
await factories.post.truncate()    // instance method shorthand
```

### Seeder.once — idempotent seed blocks

```js
import { Seeder } from '@frontierjs/litestone/testing'

class BaseSeeder extends Seeder {
  async run(db) {
    await this.once(db, 'base-v1', async () => {
      await db.account.createMany({ data: [{ name: 'Acme' }, { name: 'Globex' }] })
    })
    // runs once and never again, even across deploys
  }
}
```

---

## SQLite utilities

```js fragment
// Hot backup — safe during writes
await db.$backup('./backups/prod.db')
await db.$backup('./backups/compact.db', { vacuum: true })

// Cross-database queries
db.$attach('./archive.db', 'archive')
// asSystem(): raw SQL enforces no access rule, so a schema that declares one
// reaches it through the documented bypass only.
const rows = await db.asSystem().sql`SELECT * FROM user UNION ALL SELECT * FROM archive.user`
db.$detach('archive')

// Schema introspection
db.$schema           // augmented parsed schema (includes auto-generated models)
db.$databases        // { main: { driver, access, path }, ... }
db.$softDelete       // { ModelName: boolean } — a copy, on every flavor of client
db.$enums            // { EnumName: ['val1', 'val2', ...] }
db.$scopes('post')   // the @@scope names this model declares
db.$tenancy          // the resolved tenancy { } block, or null
db.$plugins          // installed plugin names, in run order
db.$cacheSize        // { read: 24, write: 8 }
db.$close()

// Writes and the trail
await db.$rotateKey(newKey)             // re-key every @encrypted/@secret; refused while @hashed or rotate: false exists
await db.$audit({ operation, model, records, actorId, meta })
const stop = db.$tapEvents(e => …)      // every write, announced
db.$checkWhere('post', where)           // is this a valid filter?
db.$checkOrderBy('post', orderBy)       // …and a valid sort?
await db.$lock('nightly-sweep', fn, { wait: 5_000 })  // an application-level lock; no `wait` is try-once
```

**`db.$plugins` is worth knowing about**: a schema declaring any `@@gate`
auto-installs `GatePlugin`, so what you passed is not necessarily what is running.

**A capability that depends only on the schema lives on every flavor of client**
— root, `$setAuth`, `asSystem`, `$scopedBy`. Both `$check*` and `$audit` are in
that set.

---

## Litestone Studio

```bash
bunx litestone studio   # → http://localhost:5502
```

- **Browse** — paginated table viewer, inline cell editing, soft-delete toggle, DB filter pills
- **SQL Query** — raw SQL editor across all databases
- **Schema** — ER diagram, draggable, color-coded by database, auto-generated models badged
- **Migrations** — applied/pending status + live schema diff per database
- **Stats** — per-database: page size, WAL mode, row counts, cache size
- **REPL** — Litestone query REPL with autocomplete, history, and **SQL log** per expression
- **schema.lite** — live editor with debounced validation, Ctrl+S save, error tray
- **Transform** — anonymize/shard pipeline (dev tool)
- **Performance** — schema advisor + query analyzer (EXPLAIN QUERY PLAN)

Acting-as picker: select any user from your `@@auth` model to browse with policies enforced.

---

## Shipping a schema change

**A schema change is a deploy question before it is a migration**, and
`litestone release` is the one that asks it: *can the release still serving and
the release starting share one database?*

```bash
litestone release --from=<ref|path>     # expand, contract, or unknown
litestone release --strict              # exit 1 on anything but expand or unchanged
```

**Expand** — N-1 keeps working, so the deploy can be taken back. **Contract** —
it cannot, and that deploy is the **pivot**, after which only forward. Unknown
counts as contract. `db/release.snapshot.md` is the surface it diffs, and
`--strict` fails a branch on anything but expand or unchanged, *including no
baseline at all*.

**Access is in the comparison, which is the half no generic deployer can reach**:
raising a `@@gate` takes reads away from a release still serving them, and adding
an `@@allow` empties a screen with a 200. A required column with no default is the
one contract handed back as a **plan** — expand, backfill, contract — rather than
a refusal.

`litestone access` is the same walk graded on a second axis:

```bash
litestone access                  # write db/access.snapshot.md — the whole declared
                                  #   surface: gates, policy predicates, protected
                                  #   fields, transition gates. --check in CI
litestone access --from=<ref>     # what did this branch do to WHO MAY DO WHAT?
                                  #   graded widens / narrows / undecidable
```

**It is not `release --from` with a different word.** The two grade one comparison
on axes that disagree by construction: removing a `@@gate` is an *expand* for the
deploy and the widest thing a schema change can do to access. What no comparison
can answer is a predicate whose text moved, and that is reported rather than
guessed.

`litestone ddl` is the sibling for the opposite problem — `db/ddl.snapshot.sql`
is the emitted DDL, so the names every hand-written statement binds to are a diff
rather than a surprise.

---

## CLI reference

```
litestone init                       scaffold schema.lite + litestone.config.js

litestone migrate create [label]     diff schema → write a migration file
  --rename Model.old=new               keep a renamed column's values (repeatable)
  --operations ops.json                the same, as a document
litestone migrate dry-run [label]    preview the SQL, write nothing
litestone migrate apply              apply pending migrations
                                       --backup[=dir]  copy every database first —
                                                       there is no down
litestone migrate status             applied / pending / modified
litestone migrate verify             does the live db match the schema
litestone db push                    apply the schema directly, no files (dev)
  --accept-data-loss                   allow a change that drops a column and its values

litestone types [out.d.ts]           TypeScript declarations from the schema
  --only=User,Post                     specific models only
  --audience=client|system             field visibility (default: client)
  --augment=junction                   also types client.service(name) in the browser
litestone jsonschema                 JSON Schema from the schema
litestone jsonschema --snapshot      the committed snapshot (--check in CI)

litestone studio [--no-open]         the browser UI
  --gate <path[#export]>               grade previews with this app's own getLevel
  --host <addr> --token <secret>       serve beyond loopback; the token is required there
litestone repl                       a console that boots at a standing
  --as <who> | --level <0-9> | --gate <path[#export]>
  --eval '<expr>'                      evaluate one line, print it as JSON
  --tenant <id>                        whose database, under strategy database
litestone export <dataset> --as <who>  take an @@export extract, graded as that account
litestone doctor                     check setup, audit health
litestone diagram                    ER diagram (opens in studio)
litestone explain [@word]            what a .lite word is, what it accepts, where it is legal
litestone catalog --snapshot         write the language surface (--check in CI)
litestone catalog --reference        write docs/reference.snapshot.md (--check in CI)
litestone advise                     what this schema says wrong, and what it never said
litestone validate                   which STORED rows this schema would now refuse
litestone assistant                  a chat-model schema assistant, with this schema, to paste

litestone seed [SeederClass]         seed the database
litestone seed run [name]            run an infrastructure seed (--force to re-run)
litestone introspect <db>            reverse-engineer db → schema.lite
litestone import <path>              a Prisma/Rails/Postgres/Frappe schema → .lite,
                                     graded by what the reading could not express
litestone edge eject <Model>.<field> promote an @edge/@scoped field to a real model [--apply]
litestone optimize [table]           merge FTS5 index segments
litestone transform [config.js]      anonymize / shard pipeline (dev only)

litestone backup [dest]              back up every database (SQLite + JSONL/trail)
                                       --vacuum  compact first
litestone replicate [config.js]      stream every SQLite WAL to S3/R2 via litestream
litestone restore [config.js]        bring every db back from its replica — all or nothing
                                       --at=<instant> --from-backup=<dir> --verify=<dir>
litestone rsync <dest>               sync every SQLite db via sqlite3_rsync

litestone tenant list|create <id>|delete <id>|migrate

litestone access                     the access snapshot (--check in CI)
litestone access --from=<ref>        the permission diff (--strict to gate a branch)
litestone ddl                        the DDL snapshot (--check in CI)
litestone release --from=<ref>       classify the deploy: expand / contract / unknown
                                       (--strict: exit 1 unless expand or unchanged)
litestone mutate                     mutate the schema, report what the checks miss

Global flags:
  --schema=<path>       .lite file          (auto-detected if omitted)
  --config=<path>       litestone.config.js
  --db=<path>           database file
  --migrations=<dir>    migrations directory
  --env-file=<path>     load env vars       (default: ./.env.local then ./.env)
  --no-env              skip .env loading
  --debug               print stack traces
  --version
```

**`litestone repl` boots at a standing, and the default resolver is usually the
wrong one.** `--as <who>` grades with the built-in `FrontierGateGetLevel` unless
`--gate <path[#export]>` points at the application's own — and the two disagree
by exactly the amount an app's role mapping adds. Measured on this repo's
`example`, the gap is one level on a real row, which straddles the `4` in
`@@gate(0.4.4.5)`: the same create is refused in the console and permitted in
the app. A console that is *approximately* somebody's session is worse than none,
because you act on what it shows you — so the banner names which resolver
answered.

Related, and the reason `--level` is documented as the synthetic option: a level
standing carries **no `auth()`**, so every `auth().id ==` row policy matches
nothing and its model answers an empty list rather than refusing. By the result
alone that is indistinguishable from a gate refusal.

---

## Standalone binary

The CLI compiles to a single executable with `bun build --compile`. The Bun runtime is embedded and SQLite is built into it, so the result has no external dependencies — no Bun, no `node_modules`, no Litestone source on the target machine. Useful for CI images, ops boxes, and handing a migration tool to someone who doesn't run Bun.

```bash
bun run build:binary                          # host platform → dist/litestone
bun run build:binary:all                      # every target, clean first
bun scripts/build-binary.js --target=bun-darwin-arm64
bun scripts/build-binary.js --no-bytecode     # smaller, slower to start
```

Targets: `bun-linux-x64`, `bun-linux-arm64`, `bun-darwin-x64`, `bun-darwin-arm64`, `bun-windows-x64`.

```bash
./dist/litestone db push
./dist/litestone migrate apply
./dist/litestone studio            # full UI, HTML embedded in the binary
```

The binary is almost entirely the Bun runtime. Bytecode compilation is on by default — a larger file that starts faster; `--no-bytecode` trades the other way.

**What still reads from disk.** Your `litestone.config.js`, `schema.lite`, migration files, and user seeds in `./seeds/` are loaded from the working directory as usual — a JS seed gets the full ORM client exactly as it does from source. Only files that ship *inside* the package (Studio's HTML, built-in seeds) are embedded.

**One command is unavailable.** `litestone repl` drives a separate `bun repl` process and hands it a file that imports Litestone by path, so it needs the package on disk. The binary detects this and tells you to use `bunx @frontierjs/litestone repl` instead.

**If you're modifying the CLI**, two rules keep it compilable — both fail loudly at build time rather than silently at runtime:

- Import sibling modules with literal relative specifiers (`import('../core/client.js')`), never computed ones (`import(import.meta.dir + '/../core/client.js')`). Computed specifiers are invisible to the bundler; the binary builds fine and then dies with `Cannot find module '/$bunfs/root/...'`.
- Load bundled assets with `import X from './file' with { type: 'text' }`, not `readFileSync(import.meta.dir + ...)`. There is no such directory inside a binary.

Note that `--bytecode` rewrites `import.meta.dir` to the *build machine's* source path rather than `/$bunfs/root`, so never detect "am I compiled?" by inspecting it — the CLI uses a `--define`-stamped `LITESTONE_COMPILED` flag instead.

---

## Single-file library build

Separately from the CLI binary, the *library* bundles to one file. Because the package has no third-party dependencies, the only externals are runtime built-ins (`bun:sqlite`, `fs`, `path`, `os`, `crypto`, `child_process`), so a single file is genuinely self-contained.

```bash
bun run build:lib             # dist/lib/litestone.js + .d.ts + .js.map
bun run build:lib:testing     # also emits testing.js (makeTestClient, Factory)
```

`src/index.d.ts` has no relative imports, so it's copied as-is — one `.js` plus one `.d.ts` is a complete typed drop-in with no build step for the consumer.

```js fragment
import { createClient, parse } from './vendor/litestone.js'
```

**Why this exists: vendoring.** Dropping the bundle into another package pins it to *this* workspace build, instead of whatever `"@frontierjs/litestone": "latest"` resolves to from npm. The two are not interchangeable — the schema language moves between releases (`Int`/`String`/`Float` replaced `Integer`/`Text`/`Real` and the old spellings are refused), so a package silently loading the registry copy fails on schemas that are valid here. Every bundle carries a banner naming its version and git SHA:

```js fragment
// @frontierjs/litestone <version> (git <sha>) — bundled single-file build
```

Sourcemaps are emitted by default (`--no-sourcemap` to skip) — without them, stack traces point into minified output. `--no-minify` gives readable source.

**`--with-testing` uses code splitting** rather than emitting two standalone files, because `src/testing.js` pulls in the whole core and two independent bundles would carry it twice. Test helpers stay out of the default build.

Like the binary, this is Bun-only — it imports `bun:sqlite`, so it is a single *file*, not a portable one.

---

## Multi-file schemas

```lite
// schema.lite
import "./functions.lite"
import "./models/users.lite"

import "@frontierjs/auth/schema.lite"              // a package, resolved through node
import "@frontierjs/auth/schema.lite" into auth    // …landing its models in `auth`
```

**An import specifier is a path OR a package.** Relative and absolute resolve
against the importing file; anything else goes through node, so the package's own
`exports` map decides what is importable and nothing guesses at a path inside one.
That is what lets a package **ship** a schema fragment instead of every app
keeping a copy a package upgrade cannot reach.

The failure message always names both causes — not installed, or not exported —
because node distinguishes them and bun collapses both into `MODULE_NOT_FOUND`,
and branching on the code would make the error depend on which runtime read the
schema.

**`into <db>` is how the importing app says where.** A shipped fragment has to
spell some database name and only the app knows what its own are called. One rule,
stated twice: the **nearest** statement wins — an inner `into` on a nested import
beats an outer one, and any `into` beats a `@@db` written in the imported file.
Importing one file twice under two different `into`s is an error rather than a
precedence puzzle: it is merged once, so only one could hold.

Circular imports are safe (deduplicated).

**Anything that loads a schema from a PATH must use `parseFile`, never `parse`:**

```js
await Bun.write('./models/user.lite', 'model User { id Int @id }')
await Bun.write('./root.lite',        'import "./models/user.lite"')

const db    = await createClient({ path: './root.lite', db: ':memory:' })                // parseFile, internally
const again = await createClient({ parsed: parseFile('./root.lite'), db: ':memory:' })
```

`parse` is for **text with no file behind it** — an editor buffer, a git blob —
and there the caller owes the imports. A reader that gets this wrong fails
silently, in one of three shapes: a CLI reading the root file alone reports
*already in sync* while imported tables are never created; a build hands the
browser a `$defs` table with the imported models missing, so a generated form
renders nothing; and a test environment **grades a partial schema and passes** —
a green gate ladder over models it never saw, which is the worst of the three
because it is the thing that exists to catch the other two.

Both answer the same shape — `parseFile` returns `{ valid: false, errors }` rather
than throwing, so a caller that warns and keeps going does not get a stack trace
the moment a schema has a typo. An error inside an imported file names that file.


---

## Litestream

Litestone sets the pragmas Litestream requires (`WAL`, `synchronous=NORMAL`, `busy_timeout=5000` — `createClient({ busyTimeout })` or `LITESTONE_BUSY_TIMEOUT` to change it; see [docs/concurrency.md](docs/concurrency.md)). Use `db.$backup()` for point-in-time snapshots before migrations. Use `litestone replicate config.js` for continuous WAL streaming to S3/R2.

---

## Convention decisions

| Convention | Why |
|---|---|
| `STRICT` mode on by default | No silent type coercion |
| `Boolean` stored as 0/1, returned as `true`/`false` | No leakage into app |
| `DateTime` stored as ISO-8601 TEXT | Lexicographically sortable, validated on write |
| `page_size = 8192` on new databases | Optimal for modern SSDs, set-once at creation |
| `BEGIN IMMEDIATE` for transactions | No mid-transaction write-lock deadlocks |
| `WAL mode` always on | Concurrent reads during writes |
| `foreign_keys = ON` on both connections | No silent orphan rows |
| Partial indexes on soft-delete tables | Indexes only cover live rows |
| `notIn` includes NULL rows | Matches developer expectation |
| Policies compile to SQL WHERE | Filtering in SQLite, not JS — no accidental data exposure |
| `autoMigrate` for dev, file-based for prod | Mirrors Prisma's `db push` / `migrate deploy` |

---
_Source: https://npm.io/package/@frontierjs/litestone · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
