Formal verification, briefly
A test checks the runs you thought of. A proof checks every run: every request, in every order, from every value the inputs can take. Formal verification is the practice of proving that a program keeps the properties it must keep, its invariants, or laws.
historically formal verification never reached mainstream status because of the difficulty in modeling and writing proofs. it's quite difficult to model your business requirements and keep them in sync!
/create-formal-verification-skill, which writes TLA+ models and proofs with your agentThose are the two costs, and they are real. gdp-wired removes most of both, for one kind of claim: laws about stateful rules, the code that keeps a number, a status or a set between requests and decides each request from it.
Writing the proof
Usually: you write it, by hand, in a proof language (induction, case splits, lemmas).
Here: you state the law in one line, and the prover finds the proof. A small kernel checks the proof the prover found, and Lean, a proof assistant, checks it again. If the law is false, you get a real sequence of requests that breaks it instead.
Keeping the model in sync
Usually: the model lives in another language (TLA+, Lean, Coq) and drifts from the code.
Here: the model is TypeScript, and it is what you ship. rule.compiled() runs the
rule that was proven; or, if you keep your own code, rule.compare() runs both side by side and
names the first difference.
What it doesn't remove: you still decide which laws matter, and a few kinds of claim are outside what it decides. Those go to Lean or Bend, and the limits section says exactly which.
Four words
- Rule
- A state machine: params fixed for the run (a budget), the inputs each request brings (a cost), the state kept between requests (the spend), and one step that decides a request and writes the next state.
- Law
- Something that must be true of every run of the rule: “spend stays within the budget”, “a shipped order is never refunded”. Named as a sentence; one claim per law.
- Proof
- What
proveRulereturns as{proven: true, checked: true}: the prover found a proof, and the kernel checked it. Nothing you write, nothing you read. - Counterexample
- When a law is false: a real run from the start that breaks it, as params and the requests in order. It is a bug in the rule, or in the law.
Is your code a fit?
Reach for it when
- a number must stay under a limit: a budget, a quota, a rate limit, a balance;
- a status moves through steps: an order, a ticket, a subscription, a deploy;
- a check decides who may do what: roles, plans, locks, entitlements;
- something is counted or kept per key: per user, per day, per account;
- a request carries a list: an invoice's lines, a cart's items.
Not for
- rendering, layout or anything a person judges by eye;
- an arbitrary algorithm you want shipped as its proved source (that is Bend's);
- proofs that need a lemma about a recursive structure nobody stated, or products of unknowns (Lean's).
Is the rule already in your code? You may not need to write it again. In Python, TypeScript, Go, Rust, Java,
Kotlin, Swift, Ruby, Elixir, C or C++, or as an Effect service or an XState machine, state the law as one comment
over the code and run npx gdp-wired-cli check on the file. It exits 1 on a broken law and 2 on a law
it couldn't settle, so a CI job fails on both. The language guide
has each language’s law, a broken variant, the real output, and what is read, refused and set in
gdp.toml.
The repository's examples/domains/ holds 187 rules from 21 domains (finance, access control,
commerce, healthcare, games, cloud and more), each with its laws and the broken variants it refuses. Reading one
from your domain is a good second step after this page.
Your first proof, in seven steps
Every block below is real code: it is kept in the repository's
examples/guide.ts,
which the test suite runs, and each result shown is asserted there.
-
Find the rule your code already has
Somewhere in your app is a function like this one: admit a request while the spend is under a budget, each request capped. It is short, and it is exactly the kind of code that breaks in production.
// What the app does today let spent = 0 function admit(cost: number, budget: number, maxPerRequest: number) { if (spent < budget) spent += Math.min(cost, maxPerRequest) } -
Write it as a rule
The same logic, with its parts named.
natis a natural number (0, 1, 2, …);when(c, a, b)isc ? a : b; terms have methods instead of operators (s.lt(b)iss < b). Names are typed: a misspelled one is a TypeScript error.import {min, nat, rule, when} from 'gdp-wired' const budget = rule('budget') .params({b: nat, m: nat}) // fixed for the run: the budget, the cap per request .inputs({c: nat}) // what each request brings: its cost .state({s: 0}) // what is kept between requests: the spend, from 0 .step(({b, m, c, s}) => ({s: when(s.lt(b), s.plus(min(c, m)), s)})) -
Say what must always be true
A law reads the params and the state. This one says that no sequence of requests, of any costs, ever pushes the spend past the budget plus one request's cap.
const bounded = budget.law('spend stays within b + m', ({s, b, m}) => s.atMost(b.plus(m))) -
Prove it
import {proveRule} from 'gdp-wired' proveRule(budget, [bounded]) // {proven: true, checked: true}That is the whole proof. Under the hood: it holds at the start, and every step from a state where it holds leads to a state where it holds (induction over steps). The prover finds the case analysis; the kernel checks it. Require both
provenandchecked. -
Break it on purpose
Forget the cap, the bug this law exists to catch, and the proof is refused. A search from the start then turns the refusal into a real run.
import {search} from 'gdp-wired/machine' const uncapped = budget.step(({b, c, s}) => ({s: when(s.lt(b), s.plus(c), s)})) proveRule(uncapped, [bounded]) // {proven: false, goal: 'spend stays within b + m @step', stuck: 'sat', witness: {...}} search(uncapped.machine, bounded) // {params: {b: 1, m: 0}, trace: [{c: 2}]}Read the run: with a budget of 1 and a cap of 0, one request of cost 2 takes the spend to 2, past 1 + 0. Keep this broken variant in your tests next to the real rule; it is the cheapest regression test you will write.
-
Use it in your app
Ship the rule that was proven:
compiled()is plain generated JavaScript.encodeParamsandencodeInputturn your values into what the rule reads;decodereads the state back.const shipped = budget.compiled() const params = budget.encodeParams({b: 100, m: 30}) let st = shipped.init(params) for (const c of [50, 40, 70, 20]) st = shipped.step(params, st, budget.encodeInput({c})) budget.decode(st) // {s: 110}Or keep your own code, and hold it to the rule.
compareruns both on drawn and edge inputs, field by field:budget.compare({ init: () => ({s: 0}), step: ({b, m}, state, {c}) => ({s: state.s < b ? state.s + Math.min(c, m) : state.s}), }) // {checked: 2000} // Drop the cap in your code, and compare names the first difference: // {checked: 1, failure: 'budget, params {"b":57,"m":26}, after {"c":90}: // s is 26 here, 90 in the code it describes'} -
Put it in your tests
Three assertions per rule: the laws are proven and checked, the broken variant is refused, and the builders agree with themselves on concrete runs (
crossCheck).import {expect, test} from 'vitest' // or bun:test test('the budget keeps its law', () => { expect(proveRule(budget, [bounded])).toMatchObject({proven: true, checked: true}) expect(proveRule(uncapped, [bounded]).proven).toBe(false) expect(budget.crossCheck([bounded]).failure).toBeUndefined() })
Recipes
The shapes apps keep most often. Each one is proven in examples/guide.ts, except where noted.
Limits per key: per account, per day
Maps keep a number per key. A flag is a condition decided once per step. forall(k => …) makes a
law hold at every key at once.
import {bool, forall, nat, proveRule, rule} from 'gdp-wired'
const caps = rule('caps')
.params({d: nat})
.inputs({acct: nat, day: nat, ok: bool})
.maps({Acct: 0, Day: 0})
.flags(({ok, acct, day, d, Acct, Day}) => ({
granted: ok.and(Acct.at(acct).lt(1), Day.at(day).lt(d)),
}))
.step(({acct, day, granted, Acct, Day}) => ({
Acct: Acct.bump(acct, granted),
Day: Day.bump(day, granted),
}))
const dayCap = caps.law('no day passes its cap', ({Day, d}) => forall(k => Day.at(k).atMost(d)))
const once = caps.law('no account is granted twice', ({Acct}) => forall(k => Acct.at(k).atMost(1)))
proveRule(caps, [dayCap, once]) // {proven: true, checked: true}
A workflow: statuses that only move forward
oneOf is a choice of names. A step law is about one step: when narrows the
request, and after reads the state after it.
import {oneOf, proveSteps, rule, when} from 'gdp-wired'
const order = rule('order')
.inputs({op: oneOf('pay', 'ship', 'refund')})
.state({status: oneOf('new', 'paid', 'shipped', 'refunded').from('new')})
.flags(({op, status}) => ({
paying: op.is('pay').and(status.is('new')),
shipping: op.is('ship').and(status.is('paid')),
refunding: op.is('refund').and(status.is('paid')),
}))
.step(({paying, shipping, refunding, status}) => ({
status: when(paying, 'paid', when(shipping, 'shipped', when(refunding, 'refunded', status))),
}))
const neverRefunded = order.stepLaw('a shipped order is never refunded',
(_, after) => after.status.is('refunded').not(), ({status}) => status.is('shipped'))
const paidFirst = order.stepLaw('only a paid order ships',
({status}, after) => after.status.is('shipped').implies(status.is('paid').or(status.is('shipped'))),
)
proveSteps(order, [], [neverRefunded, paidFirst]) // {proven: true, checked: true}
The same workflow as a statechart
When a workflow has more than a few states, write it as a table. chart takes nested states, parallel
regions, guards (when), extended state (context and set) and a
compound's history, and compiles them to the same kind of rule. check() answers what a
chart's author asks first: every state is reached (with the run that reaches it, or a proof that none does), no
state is stuck, and no event is ambiguous.
import {chart} from 'gdp-wired'
const order = chart('order')
.states({
new: {},
active: {states: {paid: {}, shipped: {}}},
refunded: {final: true},
delivered: {final: true},
})
.on('pay', {from: 'new', to: 'active'}) // enters active.paid, its first state
.on('ship', {from: 'active.paid', to: 'active.shipped'})
.on('refund', {from: 'active.paid', to: 'refunded'})
.on('deliver', {from: 'active.shipped', to: 'delivered'})
order.check()
// {ok: true, stuck: [], ambiguous: [],
// reached: {'active.shipped': {run: [{event: 'pay'}, {event: 'ship'}]}, ...}}
const neverAfterShipping = order.stepLaw('a shipped order is never refunded',
(_, after) => after.in('refunded').not(), before => before.in('active.shipped'))
order.prove([], [neverAfterShipping]) // {proven: true, checked: true}
With XState, and model-based tests
The proof covers the logic; a model-based test checks that the app around it follows the proven rule.
gdp-wired/xstate does both. An XState machine you already ship becomes a chart with
fromXState, its laws proven and the chart held to XState's own actor with conforms. Any
rule or chart (your app needn't use XState) becomes XState logic with toLogic, so
@xstate/graph generates test paths from the proven rule
and drives your real app along them; runToEvents turns a broken variant's run into a regression test.
More in docs/xstate.md.
import {createActor} from 'xstate'
import {TestModel} from '@xstate/graph'
import {conforms, fromXState, runToEvents, toLogic} from 'gdp-wired/xstate'
const c = fromXState(orderMachine, {guards: {...}, actions: {...}}) // the machine you ship
c.prove([], [neverAfterShipping]) // {proven: true, checked: true}
conforms(c, orderMachine, createActor) // the chart against XState's own actor
const logic = toLogic(order) // the proven rule as XState logic
const model = new TestModel(logic, logic.options)
for (const path of model.getShortestPaths()) // every state the events reach
await model.testPath(path, {states: {'*': snap => expectAppMatches(snap)},
events: {pay: () => app.pay(), ship: () => app.ship()}})
const v = brokenOrder.prove([], [neverAfterShipping]) // the bug you keep, refuted with a run
const [regression] = model.getPathsFromEvents(runToEvents(brokenOrder, v.run!))
await model.testPath(regression!, harness) // fails the buggy app, passes the fixed one
A permission check
A check with no state is a pure function. Its laws say what it must never allow, given what about the request.
With gdp-ts, guard from gdp-wired/gdp
then holds every call site to the proven check
(how).
import {bool, fun, oneOf, proveDecision} from 'gdp-wired'
const canEdit = fun('can edit')
.inputs({role: oneOf('owner', 'editor', 'viewer'), locked: bool})
.returns(({role, locked}) => ({allow: role.is('owner').or(role.is('editor').and(locked.not()))}))
const viewers = canEdit.law('a viewer never edits',
({role}) => role.is('viewer'), out => out.allow.not())
const lockedDocs = canEdit.law('only the owner edits a locked document',
({role, locked}) => [locked, role.is('owner').not()], out => out.allow.not())
proveDecision(viewers) // {proven: true, checked: true}
proveDecision(lockedDocs) // {proven: true, checked: true}
canEdit.run({role: 'editor', locked: true}) // {allow: false}
An order with line items
A request may carry a list. Folds run over it (a total, a taxable part), and a lemma about the folds is proven by induction over the lines when the rule is built, then used by every law.
import {bool, nat, proveRule, record, rule, when} from 'gdp-wired'
const Line = record({amount: nat, taxable: bool})
const invoices = rule('invoices')
.params({budget: nat})
.carriesList('Lines', Line, {
total: {from: 0, step: (acc, l) => acc.plus(l.amount)},
taxed: {from: 0, step: (acc, l) => acc.plus(when(l.taxable, l.amount, 0))},
}, {'the taxable part is within the total': ({taxed, total}) => taxed.atMost(total)})
.state({spent: 0, tax: 0})
.flags(({Lines, budget, spent}) => ({fits: spent.plus(Lines.fold.total).atMost(budget)}))
.step(({Lines, spent, tax, fits}) => ({
spent: when(fits, spent.plus(Lines.fold.total), spent),
tax: when(fits, tax.plus(Lines.fold.taxed), tax),
}))
const withinBudget = invoices.law('nothing is spent past the budget',
({spent, budget}) => spent.atMost(budget))
const taxWithin = invoices.law('the tax recorded is within what is spent',
({tax, spent}) => tax.atMost(spent))
proveRule(invoices, [withinBudget, taxWithin]) // {proven: true, checked: true}
Machine integers: wrap, saturate or trap
When the code's numbers are fixed-width (a u8, an i64), say so, and say what overflow
does: 'WRAP', 'SATURATE' or 'TRAP'. Division names its rounding:
'FLOOR', 'TRUNCATING' or 'EUCLIDEAN'. Widths are 8, 16, 32 and 64, signed or
not, and Lean checks them as its own UIntN, IntN and BitVec.
import {fixedInt, proveSteps, rule} from 'gdp-wired'
const u8 = fixedInt(8, false)
const meter = (mode: 'SATURATE' | 'WRAP') => rule('meter')
.inputs({n: u8})
.state({total: u8.from(0)})
.step(({n, total}) => ({total: total.plus(n, mode)}))
for (const mode of ['SATURATE', 'WRAP'] as const) {
const r = meter(mode)
const grows = r.stepLaw('adding never lowers the total', ({total}, after) => after.total.atLeast(total))
proveSteps(r, [], [grows])
}
// SATURATE: {proven: true, checked: true}
// WRAP: {proven: false, goal: 'adding never lowers the total @step law', stuck: 'sat',
// witness: {total$0: 174, n$0: 108}} 174 + 108 wraps to 26
New in 0.51.0; the output above is from that release, not from examples/guide.ts.
More shapes, each in the README: sliding-window rate limits over a log of requests, sums over every
key of a map (M.sum()), laws over up to 64 steps in a row, “every ticket issued is eventually served”
(under weak or strong fairness), an implementation that behaves like a simpler spec, functions defined by a
recurrence with lemmas you state, and rules read from your own TypeScript.
What it proves ·
Writing laws
Reading a verdict
Every prove call returns {proven, checked, goal?, stuck?, witness?, why?}.
| You get | It means | Do |
|---|---|---|
proven: true, checked: true | The kernel checked a proof of every goal. | Done. Keep the broken variant as a test. |
stuck: 'sat' at @start | The law is false in the start state. | Fix the start state or the law, or add .pre if those params are impossible. |
proven: true, checked: true with assumes | Proven with a helper law the prover found (below); it holds in every state a run reaches from the start. | Paste the helper from found next to your law. If your code steps the rule from states it is handed, prove with {from: 'any'}. |
stuck: 'sat' at @step | A step can take a state where the laws hold to one where this law fails, and the prover's own search found neither a helper that proves it nor a run that breaks it. That state may be one no run reaches. | Run search for longer runs. A run that comes back is a real bug. No run: the law needs a helper law the search didn't find; state it next to this one in the same call. |
stuck: 'unknown' | The prover ran out of budget; why says which limit. | Split the law into laws about fewer conditions, or use fewer steps. |
proven: true, checked: false | The kernel rejected the prover's proof. | A bug in gdp-wired: report it with the rule. Never ship on it. |
Never weaken the law that matters to make it pass, and never widen .assume to hide a
bug: an assumption is a claim about every request your code will ever see. “The search found nothing” is not a
proof.
When the law needs a helper
Some laws are true but can't be proven alone: a step from a state no run ever reaches would break them, so the
proof needs a second law that rules those states out. Writing that helper is the hard part of a proof by hand.
gdp-wired looks for it itself. When the prover alone stops and no run breaks the law, proveRule and
proveSteps search for the missing law (lemmas first, then invariants), prove it together with yours,
and hand it back as source to paste.
A connection pool: nothing is released that was not acquired. True, but not provable alone.
import {nat, oneOf, proveRule, rule, when} from 'gdp-wired'
const pool = rule('pool')
.params({size: nat})
.inputs({op: oneOf('acquire', 'release')})
.state({inUse: 0, acquired: 0, released: 0})
.flags(({op, size, inUse}) => ({
got: op.is('acquire').and(inUse.lt(size)),
back: op.is('release').and(inUse.gt(0)),
}))
.step(({inUse, acquired, released, got, back}) => ({
inUse: when(got, inUse.plus(1), when(back, inUse.minus(1), inUse)),
acquired: when(got, acquired.plus(1), acquired),
released: when(back, released.plus(1), released),
}))
const law = pool.law('nothing is released that was not acquired',
({released, acquired}) => released.atMost(acquired))
proveRule(pool, [law], {search: false})
// {proven: false, goal: 'nothing is released that was not acquired @step', stuck: 'sat'}
proveRule(pool, [law])
// {proven: true, checked: true,
// assumes: {states: 'reachable', laws: ['inUse + released <= acquired']},
// found: {laws: [{text: 'inUse + released <= acquired',
// source: "r.law('inUse + released <= acquired', ({inUse, acquired, released}) =>
// inUse.plus(released).atMost(acquired))"}]}}
The prover found the law nobody wrote (whatever is in use plus whatever came back never exceeds what was handed out), proved both, and the kernel checked the proof. The output is from gdp-wired 0.51.0, where the search took under two seconds.
- Paste what it found.
foundholds each helper as ther.law(...)call that states it, and lemmas about recurrences and lists the same way. Keep the helper with your law: the proof needs both. - Read
assumes. A helper it finds holds in the states a run reaches from the start, and the verdict says so. If your code steps the rule from a state it is handed (a stored one, another service's), prove with{from: 'any'}and requireproven && checked && !assumes: then the search never adds a helper, and the pool above is refused, rightly, until you state one that holds from every state. - Set the allowance. The search gets 10 s by default;
{search: {ms}}changes it, and{search: false}runs the prover alone. A false law still comes back with the run that breaks it: drop theinUse.gt(0)check on release and the same call returnsrun: {params: {size: 2}, trace: [{op: 1}]}, one release (choice 1) from the start. - Call the parts directly.
inferLaws(rule, laws)fromgdp-wired/inferfinds invariants (bounds, sums and differences, parities, laws about every key of a map);discover(rule, laws, stepLaws)fromgdp-wired/discoverfinds the lemmas a recurrence or a list's folds need.
What it won't prove
gdp-wired decides one kind of claim automatically. These are outside it, by design rather than for lack of a feature:
- Proofs it would have to invent. Induction over a recursive structure whose proof needs a
lemma nobody stated and the lemma search doesn't find, and arithmetic with products of unknowns beyond what
products of facts and sums of squares give. A lemma you state about a recurrence is proven, and
gdp-wired/datafinds the induction for a recursive datatype as a value. - Shipping an arbitrary algorithm as its proved source. gdp-wired ships the rule as JavaScript; Bend compiles the proved source itself.
- Values past 253. The runtimes refuse params and inputs that aren't naturals below 253, where the proofs over the naturals stop describing the run.
Where a rule needs one of those, prove that piece in Lean (a function and its facts) and give the rule the function; the rule's own laws stay automatic. The full scope, side by side with Lean and Bend.
With a coding agent
gdp-wired was built for agents to write: the skill teaches yours the workflow on this page (write the rule as the code does it, state the laws a reviewer would ask about, read a refused proof, keep the broken variant).
Let your agent consult the prover while it codes
Since 0.50.4 the package installs gdp-wired-agent-consult, an MCP server (stdio, no model
credentials, no network) that an agent calls in the middle of an edit instead of at the end. It sends the rule
and the laws as data, never code to run, and gets checked answers back:
prove- Each law, proven and checked, or not. Only
provenandcheckedtogether count as a proof;okalone isn't one. why_not- A real run from the start that breaks the law, in the rule's own names. Finding no run doesn't prove the law.
suggest- The helper laws that would prove it (the search of When the law needs a helper), returned only with the laws they were checked with.
check_change- The same laws on the rule before and after an edit: what newly breaks, with its run, and which proofs were lost.
status- What was checked for a revision, by its digest; never a label the caller supplies.
{
"mcpServers": {
"gdp-wired": {
"command": "/absolute/path/to/node",
"args": ["/absolute/path/to/node_modules/gdp-wired/dist/core/agent-consult/cli.js"]
}
}
}
A sixth tool, check, reads a TypeScript, JavaScript or Python file the way
gdp-wired-cli check does. It is off until the server itself names trusted folders, and it may run
project code, so it is not a sandbox. A proof here is about the model the agent sent: it doesn't certify that the
shipping code matches it.
Agent-consult setup and scope.
With the skill installed, ask for the claim in words:
- “Prove with gdp-wired that our refund flow never refunds an order twice.”
- “Model the per-user rate limit in
limits.tsas a gdp-wired rule and hold the existing code to it withcompare.” - “This law came back
stuck: 'sat'. Is it a bug or a missing helper law?”
Cheat sheet
| For | Use |
|---|---|
| Kinds | nat upTo(k) bool oneOf(...) maybe(kind) int decimal(places) str({like, maxLength}) record({...}) variant({...}) |
| A rule | rule(name) .params .inputs .state .maps .flags .step .assume .pre .carries .carriesList .log |
| Terms | plus minus times(k) min max when(c, a, b) count(c); conditions lt atMost atLeast eq and or not implies |
| Claims | r.law (always) · r.stepLaw (one step) · r.stepsLaw (k steps) · r.leadsTo (eventually; fairness: 'strong' for strong fairness) · r.decide and fun(...).law (one request) · r.relate (two requests) |
| Statecharts | chart(name) .states .regions .context .on(event, {from, to, when, set}) · .check() .law .stepLaw .prove |
| Every key | forall(k => ...) in a law · everyKey(k => ...) in a step · someKey(k => ...) · M.sum(), the sum of a map's cells over every key |
| Machine integers | fixedInt(8 | 16 | 32 | 64, signed) · plus minus mul negate cast with 'WRAP' 'SATURATE' 'TRAP' · div rem with 'FLOOR' 'TRUNCATING' 'EUCLIDEAN' |
| Prove | proveRule proveSteps proveDecision proveLeadsTo proveLoop |
| Helpers it finds | on by default: found (paste its source) · assumes · {search: {ms}} {search: false} · {from: 'any'} · inferLaws from gdp-wired/infer · discover from gdp-wired/discover |
| Run and check | r.compiled() r.encodeParams r.encodeInput r.decode r.compare r.crossCheck · search from gdp-wired/machine |
| From your code | npx gdp-wired-cli check <file> with a gdp: law comment · extract('./bucket.ts') from gdp-wired/extract, extractEffect from gdp-wired/effect, one per language (Languages) · fromXState from gdp-wired/xstate |
| Agents | npx skills add monotykamary/gdp-wired · the MCP server gdp-wired-agent-consult: prove why_not suggest check_change status, opt-in check · or createConsultation() from gdp-wired/agent-consult |
| Lean | toLean, leanProject from gdp-wired/lean: every proof as a Lean theorem |
Next: Writing laws (every builder) · examples/ · Why you can trust a proof · CHANGELOG