Entity / One domain declaration

Building one domain, layer by layer

The sections below walk a single catalog domain from Entity definition through server, client, and agent integration. Each snippet builds on the one above it.

1. Entities, relations, and derived members

ts
import { Schema } from 'effect'
import { Derived, Entity, Expr, Laws, Order, Query as Body, Relation, Write } from 'foldkit-entity'

const ProductFields = Entity.define(
  'Product',
  Schema.Struct({
    id: Schema.String,
    ownerId: Schema.String,
    name: Schema.String.check(Schema.isMinLength(1)),
    status: Schema.Literals(['draft', 'published']),
    stock: Schema.Number,
    reserved: Schema.Number,
    revision: Schema.Number,
  }),
)
const ReviewFields = Entity.define('Review', Schema.Struct({ id: Schema.String, stars: Schema.Number }))

const Catalog = Entity.relate(
  { Product: ProductFields, Review: ReviewFields },
  { Review: { product: Relation.one(ProductFields) } },
)

Field schemas enforce per-value constraints (name length, status enum). Declaring relations separately in Entity.relate lets mutually referencing Entities resolve cleanly without circular TypeScript inference, keeping storage column names out of the domain.

2. Derived members, invariants, and lifecycle states

ts
const Guarded = Catalog.Product.pipe(
  Entity.derived({ reviewCount: Derived.count(Catalog.Review.relations.product) }),
  Entity.invariant('reservedWithinStock', ({ after }) => Expr.lte(after.reserved, after.stock), {
    message: 'Reserved stock cannot exceed the stock',
    path: ['reserved'],
  }),
)

const Draft = Entity.refine(Guarded, 'Draft', { status: 'draft' })
const Published = Entity.refine(Guarded, 'Published', { status: 'published' })

Derived counts (Derived.count) are computed dynamically by readers so they stay consistent with reviews, invariants enforce multi-field rules, and Entity.refine names reusable states. See Laws for choosing the right declaration for each rule.

3. Authorization guards

ts
import { Guards } from 'foldkit-guard'

const User = Schema.Struct({ id: Schema.String })

const Shop = Guards.declare(
  'Shop',
  User,
  guard => ({
    isOwner: guard.row(ProductFields, user => Expr.eq(ProductFields.fields.ownerId, user.id)),
  }),
  { key: user => user.id, unguarded: 'allow' },
)

const Product = Guarded.pipe(Guards.attach(Shop, { row: { Read: [Shop.isOwner], Update: [Shop.isOwner] } }))

Authority stays separate from row validity: an owner cannot violate an invariant, and a valid row grants no permission on its own. Guards.attach returns the guarded descriptor that servers bind; see Auth and Guard.

4. Declared writes

ts
import { Mutation, Query } from 'foldkit-remote'

const Publish = Mutation.update('Publish', Product, {
  set: { status: Schema.Literal('published') },
  from: Draft,
  becomes: Published,
})

const Reserve = Mutation.update('Reserve', Product, { set: { reserved: Schema.Number } })

Each write specifies the exact fields it updates (set) plus optional from and becomes lifecycle states. Narrowing status to Schema.Literal('published') lets Laws.check prove becomes: Published statically.

When an input field name differs from the Entity field or carries extra parameters (such as an increment quantity), compose Entity.input, Write.update, and Mutation.write explicitly:

ts
const PublishLong = Mutation.write(
  'Publish',
  Write.update(
    Entity.input(Product, Schema.Struct({ ...Entity.fields(Product, 'id'), status: Schema.Literal('published') })),
    { id: 'id', from: Draft, becomes: Published },
  ),
)

Because writes are declarative data, the server needs no custom imperative handler and the browser can predict optimistic updates right away. See Declared writes for preconditions, increments, retries, and ledgers.

5. Queries and Selections

ts
const ForSale = Query.define('ForSale', { search: Schema.String }, ({ input }) =>
  Body.from(Published).pipe(
    Body.where(Expr.contains(Product.fields.name, input.search)),
    Body.orderBy(Order.desc(Product.fields.stock)),
  ),
)

const Card = Entity.select(Product, { name: true, stock: true, reviewCount: true })

ForSale defines which rows match (reusing Published) and how they sort, while Card selects which fields to fetch. Printing Body.show(ForSale.body) displays the exact query structure:

output
FROM Product
WHERE Product.Published
  AND contains(Product.name, $search)
ORDER BY Product.stock DESC

6. Checking rules without a database

ts
Laws.show(Laws.check({ writes: [Publish, Reserve] }))
output
Product
  Draft -> Published   Publish   holds
  Draft                          unreached
  Published                      terminal

Publish   x reservedWithinStock   kept: writes no member it reads
Reserve   x reservedWithinStock   refused: Reserved stock cannot exceed the stock
    before   reserved: 0, stock: 0
    input    reserved: 1
    after    reserved: 1, stock: 0

1 entity, 2 states, 2 writes, 1 rule: 2 pairs, 1 kept, 1 refused, 0 undecided

Laws.check proves Publish transitions Draft -> Published safely and flags Reserve as needing runtime enforcement at commit time. It also notes that Draft is unreached because no declared insert write creates drafts yet. Teams often check this report into source control alongside their domain, as in examples/writes/LAWS.md.

7. Wiring the server

The server maps Entity fields to Drizzle table columns and hands everything else to source, query, GuardServer.writer, and checkConstraints:

ts
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { Option } from 'effect'
import { GuardDrizzle } from 'foldkit-guard/drizzle'
import { GuardServer } from 'foldkit-guard/server'
import { bind, checkConstraints, query, source, writer, type DrizzleDatabase } from 'foldkit-remote-drizzle'
import { RemoteServer } from 'foldkit-remote-server'

const products = sqliteTable('products', {
  id: text('id').primaryKey(),
  ownerId: text('owner_id').notNull(),
  title: text('title').notNull(),
  status: text('status').notNull(),
  stock: integer('stock').notNull(),
  reserved: integer('reserved').notNull(),
  revision: integer('revision').notNull(),
})
const reviews = sqliteTable('reviews', {
  id: text('id').primaryKey(),
  stars: integer('stars').notNull(),
  productId: text('product_id').notNull(),
})

const Policy = Shop.implement({})

const Db = bind(
  { Product, Review: Catalog.Review },
  {
    Product: {
      table: products,
      fields: { name: products.title },
      visible: GuardDrizzle.visible(Policy, [Product]).Product,
    },
    Review: { table: reviews, relations: { product: { field: reviews.productId } } },
  },
)

const checks = checkConstraints(Db.Product).constraints.map(check => check.constraint)
const guarded = GuardServer.writer(Product, Policy, writer(Db.Product), { revision: 'revision' })

const server = RemoteServer.make<Option.Option<typeof User.Type>, DrizzleDatabase>({
  entities: [source(Db.Product, { filter: GuardServer.filter(Product, Policy) })],
  queries: [query(ForSale, { entity: Db.Product })],
  mutations: [RemoteServer.write(Publish, guarded), RemoteServer.write(Reserve, guarded)],
})

Notice Db requires no custom SQL for ForSale, no handler for Publish, and no mapping for reviewCount (which bind counts automatically from Review). This is where rules are enforced authoritatively.

8. Wiring the browser

The client creates a Remote instance over the exact same Product, ForSale, Publish, and Reserve declarations:

ts
import { Optic } from 'effect'
import { Can, Remote } from 'foldkit-remote'
import { ModelRef } from 'foldkit-surface'

const Model = Schema.Struct({ remote: Remote.Model })

const Data = Remote.make({
  model: ModelRef.fromOptic(Remote.Model, Optic.id<typeof Model.Type>().key('remote'), ['remote']),
  entities: [Product],
  queries: [ForSale],
  mutations: [Publish, Reserve],
})

declare const model: typeof Model.Type

const forSale = Data.query(ForSale, { search: '' }, { select: Card })

const label = Can.match(Data.can(model, Publish, { id: 'p1', status: 'published' }), {
  Yes: () => 'Publish',
  No: ({ refusal }) => `Cannot publish: ${refusal._tag}`,
  Undecided: () => 'Publish',
})

Using those shared declarations, Remote keeps cached rows inside your Model and adds three capabilities automatically:

  • Optimistic layers: Data.mutate previews changes immediately and clears the overlay once the server settles.
  • List placement: ForSale moves optimistic items into or out of cached query results when every required field is held locally, deferring uncertain lists to the server.
  • Pre-send hints: Data.can returns Yes, No, or Undecided from cached rows without guessing when fields are absent.

Forms also consume Entity.input(Product, ...) directly to generate controls, per-field rules, and invariant markers; see From declarations to the screen.

9. Wiring an AI agent

An agent exposes capabilities backed by your Message union, using Guards.may and GuardAgent.authorize to gate actions based on the permissions the server sent with each row:

ts
import { defineMessageUnion } from 'foldkit/message'
import { Agent } from 'foldkit-agent'
import { GuardAgent } from 'foldkit-guard/agent'
import { Surface } from 'foldkit-surface'

const Message = defineMessageUnion({ RequestedPublish: { id: Schema.String } })
const App = Surface.application({ Model, Message })

const Asked = Product.pipe(Guards.may)
const Row = Entity.select(Asked, { name: true, may: true })

const ShopAgent = Agent.forApplication(App).withPrincipal(Shop.Principal)

ShopAgent.expose(Message, {
  RequestedPublish: {
    description: 'Publish a product',
    authorize: GuardAgent.authorize('Update', ({ input, model }) =>
      Data.get(Row, input.id).read(model),
    ),
  },
})

If a row isn't loaded yet or its may flag forbids updates, the agent refuses early; the server still verifies guards on commit. See Agents and the guard README.