Entity / Laws
A first check with Laws.check
Suppose a Product entity forbids reserving more stock than is on hand, and a Restock write increments stock by an integer quantity:
ts
import { Schema } from 'effect'
import { Entity, Expr, Laws, Write } from 'foldkit-entity'
import { Mutation } from 'foldkit-remote'
const Product = Entity.define(
'Product',
Schema.Struct({
id: Schema.String,
status: Schema.Literals(['draft', 'published']),
stock: Schema.Number,
reserved: Schema.Number,
}),
).pipe(
Entity.invariant('reservedWithinStock', ({ after }) => Expr.lte(after.reserved, after.stock), {
message: 'Reserved stock cannot exceed the stock',
path: ['reserved'],
}),
)
const Restock = Mutation.write(
'Restock',
Write.update(
Entity.input(Product, Schema.Struct({ id: Schema.String, quantity: Schema.Int }), {
quantity: Entity.unmapped,
}),
{ id: 'id', increment: { stock: 'quantity' } },
),
)
const report = Laws.check({ writes: [Restock] })
Laws.show(report)Running Laws.show(report) prints:
output
Product
Draft? (no states declared)
Restock x reservedWithinStock refused: Reserved stock cannot exceed the stock
before reserved: 0, stock: 0
input quantity: -1
after reserved: 0, stock: -1
1 entity, 0 states, 1 write, 1 rule: 1 pair, 0 kept, 1 refused, 0 undecidedBecause quantity allows negative integers, Laws.check finds a concrete counterexample (stock: 0, quantity: -1, leaving stock: -1) without touching a database. You can either narrow quantity with Schema.isGreaterThanOrEqualTo(0) so Restock is proved kept, or rely on the server writer to refuse negative stock at commit time.