Metakit / Verify a state machine

Pin critical transitions and allow opaque ones explicitly

Install @doeixd/metakit and effect, and z3-solver as a dev dependency: the opaque transition below cannot be proved by the built-in checks, so this example needs the solver (see "Prove.* fails with SolverUnavailableError"). Run the file as an ES module, since it uses top-level await, or put the call inside a test.

Pass pin and allowUnknown to Prove.machine. Each names a transition by the value the machine holds for it, AccountMachine.transitions.Withdraw, so a misspelt name fails typechecking on its line. allowUnknown is a list of [transition, reason] pairs.

ts
import { Effect, Schema } from 'effect'
import { Eq, Expr, Num, Transition } from '@doeixd/metakit'
import * as Machine from '@doeixd/metakit/machine'
import * as Prove from '@doeixd/metakit/prove'

const Account = Schema.Struct({
  balance: Schema.Int,
  reserved: Schema.Int,
  status: Schema.Literals(['open', 'frozen']),
}).pipe(
  Expr.refine($ =>
    Expr.all(Num.gte($.balance, 0), Num.gte($.reserved, 0), Num.lte($.reserved, $.balance)),
  ),
)

const AccountMachine = Machine.make({
  state: Account,
  transitions: {
    Withdraw: Transition.make({
      state: Account,
      input: Schema.Struct({ amount: Schema.Int }),
      when: ({ state, input }) =>
        Expr.all(
          Eq.is(state.status, 'open'),
          Num.gt(input.amount, 0),
          Num.lte(input.amount, Num.sub(state.balance, state.reserved)),
        ),
      apply: ({ state, input }) => [
        Transition.set(state.balance, Num.sub(state.balance, input.amount)),
      ],
    }),
    ExternalReconcile: Transition.make({
      state: Account,
      input: Schema.Struct({}),
      when: ({ state }) =>
        Expr.opaque({ name: 'fraudCheck', reads: [state.balance] }, () => true),
      apply: ({ state }) => [Transition.set(state.balance, Num.sub(state.balance, 1))],
    }),
  },
})

const report = await Effect.runPromise(
  Prove.machine(AccountMachine, {
    pin: [AccountMachine.transitions.Withdraw],
    allowUnknown: [
      [AccountMachine.transitions.ExternalReconcile, 'Calls external fraudCheck callback'],
    ],
  }),
)
// report.ok -> true
// report.format():
//   PROVED (zone) Withdraw [pinned]
//   UNDECIDED (allowed: Calls external fraudCheck callback) ExternalReconcile: ...

What happened: Withdraw is proved, and the label (zone) names the checker that proved it (concrete, interval and zone run in the same process, z3 is the solver). ExternalReconcile reads an opaque function, so it stays undecided; its reason in allowUnknown makes that acceptable, and the line prints the reason beside the result. report.ok is true.