Guard / How Guard works

How Guard, Expressions, and Laws act like a constraint solver

A constraint solver takes rules over typed variables and narrows what is possible: it filters valid solutions, simplifies partial facts, detects impossible paths, and proves when changes stay safe.

In Foldkit Plus, you write all of your rules in the same Expr language: field Schemas, table rules (Entity.invariant), named row states (Entity.refine), write preconditions (when / from), query filters (Query.where), and foldkit-guard row rules. Every write succeeds only when all four hold together:

Authorization (Guard) AND precondition (from, when) AND invariants (before, after) AND Schema

Those shared declarations act as a constraint system across three layers:

1. Live enforcement and SQL filtering

On reads, GuardDrizzle.visible combines your Read condition with your query's WHERE clause into one SQL statement, so the database solves for every row meeting both constraints.

On writes, GuardServer.writer and your declared writer refuse any commit that breaks a guard, precondition, or invariant, while SQL CHECK constraints protect one-row invariants against raw SQL. Every stored row is therefore guaranteed to hold your state invariants, and checking Update row guards on both before and after turns row guards into transition constraints per actor.

2. Partial evaluation and residualization

When only some values are known, Guard and Judge (the in-memory expression evaluator in foldkit-entity) simplify the constraints instead of guessing:

  • Policy.readable evaluates every principal guard once and folds the boolean tree to Always, Never, or only the row guards left over.
  • Condition.residual(condition, row, input, operators) checks every single-row guard against row right away and keeps only cross-row guards (Expr.path, Expr.exists) for the SQL statement.
  • Condition.judge checks a partially held client row twice — assuming unknown guards are true, then assuming false. Because a Condition contains no not, whenever both runs agree the answer is exact; otherwise it stays undecided.
  • Data.can (from foldkit-remote) evaluates a row's may, the write's when / from, and the Entity's invariants over client rows in the server's order (Forbidden, Unmet, Invalid). Your UI and AI agents can check which actions can succeed before sending a request.

3. Static constraint propagation with Laws.check

Because invariants and declared writes are Expr data, Laws.check (from foldkit-entity) runs a built-in, synchronous constraint solver over your declarations with no database. It enumerates finite fields (booleans and literal unions) and propagates numeric intervals from Schema bounds, when conditions, and assumed invariants through write operations using their declared monotonic laws.

This example defines an Account invariant (balance >= 0) and a fee write (Write.update with Entity.input for the write's arguments), then proves statically that the fee can never overdraw an account:

ts
import { Schema } from 'effect'
import { Entity, Expr, Laws, Write } from 'foldkit-entity'

const Account = Entity.define(
  'Account',
  Schema.Struct({
    id: Schema.String,
    status: Schema.Literals(['open', 'closed']),
    balance: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
  }),
).pipe(
  Entity.invariant('neverOverdrawn', ({ after }) => Expr.gte(after.balance, 0), {
    message: 'Balance cannot go negative',
    path: ['balance'],
  }),
)

const ChargeFee = Write.update(
  Entity.input(Account, Schema.Struct({ id: Schema.String })),
  {
    id: 'id',
    compute: { balance: ({ row }) => Expr.sub(row.balance, 5) },
    when: () => Expr.gte(Account.fields.balance, 5),
  },
)

const report = Laws.check({ writes: [{ name: 'ChargeFee', write: ChargeFee }] })
report.pairs[0]?.verdict._tag // 'Kept'

Laws.check narrows balance from when to [5, ∞), subtracts 5 through Expr.sub's monotonic law (a larger input gives a larger result) to get [0, ∞), and records one verdict in report.pairs for each write-and-invariant pair (Kept, Refused, or Undecided). Here ChargeFee is Kept for every valid account. If the narrowed range is empty, Laws.check reports Unmeetable (a dead write). If a rule can fail, it prints a concrete failing before, input, and after example checked by Judge.