Metakit / Why rules should be data

Five implications you get from that single change

1. One rule runs in JS, SQL, forms, and JSON Schema

Every reader consumes the exact same AST attached to Account. The blocks from here on continue the file above (Account, Withdraw and the imports stay in scope):

ts
// Runtime decode (standard Effect Schema)
const bad = Schema.decodeUnknownResult(Account)({
  id: 'a1',
  balance: 10,
  reserved: 20,
  status: 'open',
  promoEnabled: false,
})
// Result.isFailure(bad) -> true

// Postgres CHECK constraint
const check = Result.getOrThrow(Sql.toCheck(Account, { dialect: 'postgres' }))
// check -> CHECK ((((("balance" >= 0) AND ("reserved" >= 0)) AND ("reserved" <= "balance"))) IS TRUE)
// `IS TRUE` because SQL lets a CHECK pass when its result is null; here null fails, as it does in the Schema.

// Form field bounds & JSON Schema
const specs = Inspect.fieldSpecs(Account)
// balance spec has min: Some(0), kind: 'integer'
// status spec has literals: Some(['open', 'frozen'])
const jsonSchema = Inspect.toJsonSchema(Account)
void bad
void check
void specs
void jsonSchema

2. Partial evaluation answers "is this allowed?" before inputs exist

Transition.can evaluates Withdraw.when against whatever slice of { state, input } you have right now, returning a three-valued Verdict (True, False, or Unknown):

ts
const frozen = {
  id: 'a1',
  balance: 50_000,
  reserved: 10_000,
  status: 'frozen' as const,
  promoEnabled: false,
}
const open = { ...frozen, status: 'open' as const }

const onFrozen = Transition.can(Withdraw, { state: frozen })
// Verdict.isFalse(onFrozen) -> true  (disable the button before any input is typed)

const onOpen = Transition.can(Withdraw, { state: open })
// Verdict.isUnknown(onOpen) -> true  (account is open; waiting on input.amount)

void Verdict.isFalse(onFrozen)
void Verdict.isUnknown(onOpen)

Runtime null is kept strictly separate from missing (Unknown) fields: { discount: null } is a known null and folds immediately, while omitting discount leaves it Unknown.

3. Validity vs. authority is enforced by TypeScript

Every Expr<Env, A> is indexed by the environment Env it can read. Account's invariant has Env = Account, so referencing a principal (the signed-in user asking) inside Account's Expr.refine is a compile-time error. A policy built with Expr.in({ row: Account, principal: Principal }, ...) has both in scope. You cannot accidentally leak an authorization check into a table CHECK constraint.

4. Invariant preservation is proved—or refuted with a reproducer

Prove.machine checks every transition against Account's invariants (the rules in Expr.refine). Rules built from linear arithmetic and OrderedEnum are proved by the built-in interval and zone checkers, which run in your process without Z3, a general-purpose solver. If a guard is weakened, the solver is asked for a concrete counterexample. A pin, pin: [AccountMachine.transitions.Withdraw], says this transition must stay proved; the report is not ok otherwise:

ts
const AccountMachine = Machine.make({ state: Account, transitions: { Withdraw } })
const proof = await Effect.runPromise(
  Prove.machine(AccountMachine, { pin: [AccountMachine.transitions.Withdraw] }),
)
// proof.ok -> true
// proof.format():
//   PROVED (zone) Withdraw [pinned]
void proof

If someone removes Num.lte(input.amount, Num.sub(state.balance, state.reserved)), proof.ok becomes false and proof.format() prints:

REFUTED Withdraw [PIN BROKEN]
  before:   {"id":"model-string:0","balance":0,"reserved":0,"status":"open","promoEnabled":false}
  input:    {"amount":1}
  after:    {"id":"model-string:0","balance":-1,"reserved":0,"status":"open","promoEnabled":false}
  violated: (((balance >= 0) && (reserved >= 0)) && (reserved <= balance))
  repro:    Transition.run(Withdraw, {"id":"model-string:0","balance":0,"reserved":0,"status":"open","promoEnabled":false}, {"amount":1})

When a transition genuinely needs arbitrary JavaScript (such as a third-party fraud callback), Expr.opaque lets it live beside declarative transitions while degrading soundly to Unknown—never fabricating a fake proof.

5. Static dependency graphs and minimal SSR payloads come for free

Because reads and writes are inspectable paths, @doeixd/metakit/graph computes which view bindings each transition invalidates, which bindings never change (deadBindings), and which model paths SSR must serialize after folding static flags:

ts
const $ = Path.from(Account)
const bindings = {
  available: Num.sub($.balance, $.reserved),
  accountId: $.id,
  promoBonus: Expr.when($.promoEnabled, { then: Num.sub($.balance, $.reserved), else: 0 }),
}

const analysis = Graph.analyze(AccountMachine, bindings)
// analysis.affectedBy.Withdraw -> ['available', 'promoBonus']
// analysis.deadBindings        -> ['accountId']

const pruned = Graph.pruneStatic(bindings, { promoEnabled: false })
// pruned.staticValues -> { promoBonus: 0 }
// pruned.resumePaths  -> Some([['balance'], ['reserved'], ['id']])
// `accountId` is dead (no transition writes `id`), but the page still reads it, so `id` stays.
void analysis
void pruned

What stays in plain Effect

@doeixd/metakit deliberately stops at single-step, synchronous expressions and transitions:

  • I/O, concurrency, retries, and services stay in Effect (a Transition returns the records listed in emits, each Transition.emit(tag, fields), for your Effect runtime to turn into Commands).
  • Encoding, decoding, and bidirectional codecs stay in effect/Schema.
  • Rendering and layout stay in your UI layer.

Next