Skip to content

Latest commit

 

History

History
978 lines (862 loc) · 62.6 KB

SPEC.md

File metadata and controls

978 lines (862 loc) · 62.6 KB

Spec reference

The spec format, the generated code and the code built on it. The procedure is AGENTS.md; the agent's loop is the sync skill; the stages of pnpm check are below.

A path under vibestack/ names a file of the vibestack repository, which the installed package does not ship. There, "the order example" is vibestack/examples/order/spec/index.md and "the tracker example" is vibestack/examples/dashboard/spec/tracker.md. The root spec/index.md links to spec/app/index.md, the hello world in apps/app that uses one of each thing Vibestack offers (apps/app/README.md), to be replaced by your application.

Stages of pnpm check

Each line of a report names its stage: ✓ passed, ✗ failed, - skipped, with the reason.

Stage Checks Skipped when
model each spec parses, and its Quint typechecks never
always always rules and laws hold on simulated traces; leadsTo rules on fair runs the spec is not a valid model
sometimes each sometimes goal is reached, and each event happens in some simulated state the model is invalid, or simulation stopped at an always failure
replay the generated TypeScript agrees with Quint on the simulated traces as sometimes
types the vibelang compiler checks src/, the tests and gen/ (shell skill) a stage above failed; without a tsconfig.json it passes as skipped only when there is no src/ or test/
proof Dafny proves each unit's obligations, or spec/lock.json records them as simulated only a stage above types failed; it runs beside types
tests the package's tests pass, each cites a story or rule the spec has and reaches past gen/, and its drivers import gen/ as types only a stage above failed
traces the application, through its drivers, driver: programs and recorded traces, agrees with the spec (Conformance) a stage above failed
explore Bombadil explores the package's page, served by its start or dev script, and the properties of test/bombadil.ts, or Bombadil's defaults, hold in every state it reaches (Exploring the page) a stage above failed; a - line on a platform Bombadil has no executable for
review every story, rule and contract changed since spec/lock.json was recorded; without sign-off a check that passes everything else records it (Review) never

Types and proofs start once every model is valid, and run while the simulations do; they are reported only if every simulation passed, and otherwise finish unreported before the check returns. Tests, traces and explore wait for all three.

Writing a spec

pnpm exec spec new fills an empty spec/index.md with a starter that passes every stage but review. pnpm exec spec new <name> writes spec/<name>/index.md; nested names such as billing/payments are allowed. A non-empty spec is never replaced.

check reads every spec/**/*.md, including child directories. A spec may link to another with [Payments](./payments/) or [Currency](../shared/currency.md). Directory links resolve to index.md; references stay inside spec/. Links organize the spec; Quint imports bring in definitions. An empty index or one containing only navigation links is valid. A ## story still needs rules.

Each path component uses [a-z][A-Za-z0-9]*. The generated module name is the path relative to spec/, without .md or a trailing /index, with slashes replaced by __: spec/index.md becomes gen/index.ts, spec/billing/index.md becomes gen/billing.ts, and spec/billing/payments.md becomes gen/billing__payments.ts. Flat files remain supported. Two paths cannot name the same module, so use either spec/billing.md or spec/billing/index.md. In a monorepo, spec/billing/ belongs to the package apps/billing or packages/billing, which gets these modules in its own gen/ under the same names (One spec tree).

# Order checkout                         <- title, free text

## Story: Check out                      <- a story

> As a shopper, I want to …              <- the story's text

### Only a non-empty draft can be submitted      <- a rule: one checkable sentence

Submitting freezes the order.            <- the rule's prose, optional

```quint
pure def canSubmit(o: Order): bool = o.status == Draft and o.units > 0
pure def submit(o: Order): Order = { ...o, status: Pending }
```
Line Means
## … a story, or any group of rules. Needs at least one rule. Its text runs to its first ###
### … a rule, keyed <story> / <heading>, unique in the spec. Needs a quint block
```quint the rule's formal half; only under a ###
any other fence prose; ## and ### inside it are not headings
####, bold, anything else prose of the rule or story above

A fence is three or more backticks or tildes. It closes only on a line of the same character, at least as long, with nothing after it, so a fence of four backticks can hold a ```quint example. A fence is Quint when the first word of its info string is quint.

Quint errors are reported at the source file's path and line:col.

What goes in the Quint blocks

Only types, imports, pure val, pure def and the const of an opaque function. There is no var, no action, and no init or step: the state machine around your definitions is generated. The role of a definition comes from its name and signature:

You write It is Generated from it
type Order = { … }, type Status = A | B the vocabulary interface Order, type Status = "A" | "B"
pure val initial: Order = … the initial state; its type is the state type. A spec without one is a library initial, parseState, and a proof that it satisfies every always rule
pure def pay(o: Order, amount: int): Order a transition: any pure def whose first parameter is the state and that returns the state pay(o, amount), an Event variant { type: "pay", amount }, a case in step, enabled and parseEvent, and proofs that it preserves every rule
pure def canPay(o: Order, amount: int): bool the guard of pay; takes the state and any subset of its other parameters, matched by name and type canPay, used by enabled and step. What is proved about pay is proved for the cases the guard allows. A guard may call its own transition to look at the result
pure def alwaysPaidWithinDue(o: Order): bool a rule that holds in every reachable state a conjunct of inv; simulated and proved
pure def stepNeverGoesBack(before: Order, after: Order): bool a rule about every single step a postcondition on every transition; simulated and proved
pure def stepAuthorized(before: Order, via: str, after: Order): bool a step rule that also sees the transition name a postcondition on every transition
pure def sometimesPaid(o: Order): bool a state that must be reachable a reachability check with a witness trace
pure def refinesL(s: Switch): L::Lamp the spec refines the machine imported as L an obligation on every transition and on initial; simulated and proved
pure def leadsToPaid(o: Order, later: Order): bool a liveness rule: from every reachable state o, every fair run reaches a state later that it relates to o (o itself counts) a search of simulated traces for a fair run that breaks it ("Liveness", below)
pure def lawTotalIsNotNegative(xs: List[int]): bool a law: true for every value of its parameters a function proved to return true, and sampled by the simulator
const hash: (str) => int an opaque function: a type and no body. The laws in its rule are assumed of it see Opaque functions
type NoteId = str a name for a string or an integer type NoteId, which a bare string is and gives, and which no other named string is: in what an event carries, a SessionId is not sent for a NoteId
pure def isOpen(p: Phase): bool = p == Draft or p == Open a predicate on one plain sum isOpen; and, where it holds of some variants and not of others, the type of those, OpenPhase (the predicate's name without is, then the sum's). In the Effect adapter isOpen(p) narrows p to it
pure def validGeometry(g: Geometry): bool a check: a predicate named valid… on one value of a type that is not a plain sum validGeometry, a type guard to ValidGeometry, the values it holds of, which no other value passes for (Checked values)
pure val holdRoute: Endpoint = { …, machine: reflected } an instance of a kind the spec imports a constant of gen/<name>.ts, once it meets every rule of its kind (Kinds and instances)
type SecretCard = str a secret: a type named Secret… type SecretCard, a brand the program can hold but not read; check keeps its values out of every other place (Secrets)
pure def declassifyLast4(c: SecretCard): str the one way out for a secret a function that takes the brand and returns a public value; review names it
pure val idValues = Set(1, 2, 3) what the simulator tries for a parameter named id. It must be a set whose elements match the parameter type; any supported Quint is allowed in it nothing: it never reaches TypeScript
pure val weight_pay = 5 how often the simulator tries pay: a whole number from 1 to 100, times as often as an event of weight 1 (the default). For deep interleavings, such as a message lost, repeated and reordered nothing
pure val eval_witness_sometimesPaid = (("authorize", 8), ("pay", 8), "finish") an example path from initial to the named sometimes rule nothing
pure val eval_witness_canPay = (("authorize", 8), ("pay", 8)) an example path from initial whose final transition is guarded by canPay nothing
pure val eval_refuse_canElapse = { elapsed: -1 } concrete arguments for a transition guard to refuse in initial nothing
pure val fair_pay = "weak" or "strong" an assumption for leadsTo rules: a fair run does not put pay off for ever while its guard keeps allowing it ("weak"), or while it allows it again and again ("strong") nothing
pure val within_leadsToPaid = 3 a bound for a leadsTo rule: every run meets it within 3 events, from 1 to 100 a search of simulated traces for a run that does not ("Liveness", below)
any other pure val or pure def a constant or helper the same constant or function

Each goal search can also uncover a broken rule. If the search finishes without a witness, a retained probe that evaluated the goal to true can supply its journey through the usual TypeScript replay when the spec gives no example. When a reachability search uses multiple trace lengths, it tries short, single-threaded batches before spending the full search budgets. Give a eval_witness_<rule> for a goal that needs a rare sequence or specific values. Write each step as a transition name followed by its arguments in declaration order. A step with no arguments is just its name. For one step, write that step alone. In a model with senders, add the sender last for a transition that does not take by.

Quint typechecks the arguments and runs the original transitions and their guards, checking state and step rules until the path reaches the goal or breaks a rule. A broken rule fails the check. The usual search runs if the example stops short of the goal. The safety and probe samples stay the same, and a trace that reaches the goal or breaks a rule goes through the usual replay. An ordinary simulation can reuse its results when only an unused guide changes. The check preserves the input files for replay when one of these ordinary runs fails.

An eval_witness_<guard> uses the same transition syntax. Its last transition must have the named guard. When an allowance along the path is still missing, Quint tries the path from the initial state. A completed path shows each fired transition's guard allowed it. The checker replays the path through generated TypeScript, includes the fired events in the conformance inputs, and runs the usual search for each allowance still missing. A state or step rule broken along the path fails the check.

An eval_refuse_<guard> record has one field for each of the guard's sampled arguments. In a model without opaque functions, if other traces have not shown a refusal, Quint tries the given arguments in the initial state. A valid refusal replaces the remaining randomized refusal search and goes through TypeScript replay. If the example does not show a refusal, the usual search runs. The ordinary safety and probe samples and the application conformance inputs are unchanged by the focused trace.

A transition parameter named by identifies its sender. All such parameters use the same type. It is supplied separately as enabled(current, event, by) and step(current, event, by); it never comes from parseEvent. The shell must validate the authenticated sender before supplying it. Once any transition takes by, step, enabled and Machine.send take a sender for every event, and Machine.send and apply take only one the host's sign-in made (Proofs, receipts and senders). In the generated Dafny it is by_, as a proof file's lemma headers spell it.

A helper that takes the state first and returns the state would be taken for a transition. Give it the state as its second parameter, or return something smaller.

A transition may return a named record { state: State, out: List[Effect] }. All transitions that return effects use the same record type. In that module, step returns that record; state-only transitions and rejected events return an empty out. A step rule may take a final parameter named out to inspect the effects, after the resulting state. The simulator compares those effects with the generated TypeScript, and the proof checks each such step rule.

Refused, each with a message saying why: the generated and harness names (init, step, inv, enabled, parseEvent, parseState, Event, Secret, Plain, Checked, current, event, state, …) and ProofLib; JavaScript globals and keywords (Number, delete, …); Quint built-ins (to, next, all, size, …); a parameter named like a variant; a variant field called tag; two record types with the same fields; a field __proto__; names beginning std_ (parseSpec in vibestack/parse.ts), or nth_, get_, lookup<n>_ or another prefix the generated module uses for itself (GENERATED in vibestack/gen.ts); and near-misses of the conventions above such as alwayspaid or CanPay. A state machine is also refused the names of its Effect adapter: Rejected, NotAnEvent, NotAState, NotASender, Machine, machine, machineOver, stored, apply, decodeEvent, decodeState and decodeSender; and any spec that declares a type is refused Schemas, under which the adapter exports the Schema of each (shell skill).

Using one spec from another

Import paths resolve relative to the spec that contains them. For example, import currency.* from "../shared/currency" uses a sibling area's library, and import payments as P from "./payments" uses payments/index.md. Generated code uses the imported spec's full module path.

  • import kernel.* from "./kernel" takes a library's names as they are. A library is a spec with no initial: definitions and laws, or a component such as an account with canWithdraw and withdraw and no state of its own (vibestack/fixtures/account.md in the vibestack repository, used by bank.md).
  • import lamp as L from "./lamp" takes any spec under a name, a state machine included. A room can then hold two L::Lamps in its state, start them from L::initial, move them with L::toggle, require L::alwaysFlipsAreCounted of each, and add rules about the pair that neither lamp could state (vibestack/fixtures/room.md in the vibestack repository).
  • import net as N from "./net" takes a spec that ships with the tools, from their std/ directory, when the importing spec's directory has no net.md or net/index.md. It is simulated and proved with the specs that import it, never reviewed. vibestack/std/net.md is a network that loses, repeats and reorders: the numbers of the messages in flight, with N::send, N::take (to deliver or lose one), N::repeat, and laws for an always rule that only messages sent are in flight. vibestack/fixtures/ping.md uses it.

A spec is imported once, one way or the other, and imports cannot form a circle. Navigation links may point back to a parent. In the generated TypeScript a name from another module is spelled <module>_<name>, for example lamp_toggle.

One spec tree

The repository has one spec tree, at its root, and one check of it.

Path Is
spec/index.md the product's requirements: an introduction, and a link to each area
spec/<name>/ the requirements of the package apps/<name> or packages/<name>, its owner, when there is one with no spec/ of its own. Nothing else says so: the name does
spec/<name>/ with no such package an area of the root project; its modules stay in the root's gen/
a package with its own spec/ a project of its own, checked on its own: Studio, each example

pnpm check at the root parses, simulates, proves and reviews the whole tree once, against the one ledger spec/lock.json, and does for each owner what it does for the root's own src/ and test/:

  • gen/. The modules of the owner's specs, and of every spec they import, are also written to <owner>/gen/ under the names they have in the root's: spec/app/index.md is apps/app/gen/app.ts, with app.effect.vibe and app.conformance.ts (its driver's types); spec/app/cart.md is app__cart.ts; a library spec/shared/money.md it imports is shared__money.ts. A package imports only from its own gen/. pnpm gen and pnpm install write it too.
  • Stages. types, tests and traces run in the owner's directory, on its tsconfig.json, test script, test/drivers/, test/traces/ and driver: scripts; its //@ files under src/ are proved and their contracts reviewed. Each result names the package: apps/app: pass.
  • Citations in an owner's code are written from the root, as everywhere: // spec/app/index.md, "A rule".

An owner has no check, gen or accept script: the root's are its own.

For an independent owner build, pnpm gen --owner <name> reads every spec in spec/<name>/ and follows its imports and links to check references. It compiles the owner's Quint and the Quint it imports, and writes the same gen/ artifact that whole-tree generation writes for that owner. Root pnpm check still checks the whole tree and owns acceptance.

Projects with non-formal directories under spec/ or custom package paths configure them in vibestack.json (or under package.json#vibestack, see vibestack/README.md, "Configuration"):

  • spec.exclude: subdirectories relative to spec/ (for example ["models", "product"]) ignored by formal parsing, generation, simulation, proofs, and review. Markdown links pointing into an excluded directory are treated as informational prose links rather than broken formal references.
  • spec.owners: maps spec area names to package directories when a package's directory differs from apps/<name> or packages/<name> (for example { "records": "packages/launcher-records" }). Merged with package.json#specOwners.
  • spec.dir, mode, cacheDir, stages: override the spec root, toolchain mode ("vibelang", "typescript", or "specs-only"), cache directory, or stage runners (types, tests, explore).

Opaque functions

const f: (A, B) => R, on one line under a rule, declares a function with no body: a hash, a check the spec does not model, a model's judgement. What the spec knows of it is the laws in the same rule; they are assumed, not proved, and review shows them with it. A law about f in another rule is proved as any law is. vibestack/fixtures/badge.md in the vibestack repository is the example.

  • Simulated as a table chosen for each trace: for each argument the simulator tries (the values of its type), a result from the values of R, or from fValues if the spec defines it. A trace starts only with a table on which every law of f holds for every value tried, so a rule that holds only for some tables is broken in simulation. If no table satisfies the laws, they may contradict each other, and always fails.
  • Proved with f uninterpreted (function {:axiom} f in the Dafny) and each of its laws as a lemma <law>_ensures(args) that a proof file calls.
  • In TypeScript the program gives it before anything calls it: opaque.f = hashName, from gen/<name>.ts; until then f throws. Its parameters are p0, p1, … Nothing proves that what the program gives satisfies the laws: prove that in src/ with a //@ contract.
  • Only simple values (int, bool, str, a plain variant) are its arguments, and a spec with an opaque function cannot be imported.

Secrets

A type whose name starts with Secret (type SecretCard = str, or a record) is secret. model refuses a spec in which a secret value can reach a place whose type is not secret: a field, a variant's field such as the text of something said, an element of a list, set or map, or the result of a transition, a guard or a helper. A value computed from a secret, or chosen by a condition on one, is secret too, through calls to helpers as well. Rules only check, so they may read secrets freely.

The one way out is a definition named declassify…: what it returns is public. Review marks a rule that defines one, whenever it is new or changed, and declassifies a secret through <name>; confirm that what it lets out may be public. vibestack/fixtures/card.md in the vibestack repository is the example, and vibestack/examples/assistant keeps a saved card out of speech this way.

A secret the outside world must receive whole, such as a key for an Authorization header or a signer, goes out through a definition named declassifyTo<Sink>, which names that one sink: pure def declassifyToAuthorization(k: SecretApiKey): str = k. What it returns is public only to the model; the lint (machine/egress) holds it to a call in an egress module, and review reads that the call is its sink. Only a module named *.egress.ts or *.egress.vibe, which review reads as it reads a *.auth.* module, may name one, and there what it returns, directly or through a const, goes into the argument of the call that sends it, inside a template, a record or a list if it must: it is never kept elsewhere, returned (by return or Effect.succeed…), exported, thrown or yield*ed in a new error, nor given, even through another call, to console, Console, Effect.log…, Effect.fail…, Effect.die…, Effect.annotate…, String, JSON.stringify or an …Error, under a const of another name too. A function the module declares, with function or as a const, is followed into: what it returns of its argument is held as the argument was. It is imported under its own name, and passed bare only as an argument, a release function another function calls: what that call returns is held as the release itself is.

In gen/<name>.ts a secret is a brand, Secret<"<module>.<Type>", <what it holds>> of gen/_machine.ts: type SecretCard = Secret<"index.SecretCard", string>. The program holds it, keeps it in a state and sends it in an event, but the compiler refuses to read it as what it holds: it is not a string, cannot be compared with one, returned or passed where one is wanted, has no toString or valueOf of its own to call, and no string becomes one. Generated code alone makes one, from what parseEvent, parseState and the adapter's decodeEvent, decodeState, receive and Schemas.<Type> decoded, and alone reads one, inside the definitions the spec wrote: the declassify… functions return what they read as public values, and a rule returns only true or false. A definition returns a secret or a plain value as its declared type says, whatever its body returns: declassifyToAuthorization(k: SecretApiKey): string, though its body returns the key, and pure def typed(s: str): SecretCard = s returns the brand. Schemas.SecretCard decodes a string into the brand and encodes the brand into itself, never into a string, so the shell takes a secret in through it: try Schema.decodeUnknownEffect(Schemas.SecretCard)(typed). The lint (machine/casts) refuses an as, or a type guard, that names a secret type outside gen/, by its own name or by another the file gives it; where the file has the program's types, as a TypeScript module of vibestackConfig does, it also refuses an as of a value, or to a type, that holds a secret in a field or a list, and such a value in a template, beside a +, given to console, Console, Effect.log… or String, or made text by its join, toString or toLocaleString. A .vibe file has no such types: there the compiler refuses only what it refuses everywhere, and a secret in a template or beside a + is the shell's to keep out. Anything else that takes unknown, such as JSON.stringify, takes a secret as its text: keep the state that holds one where it belongs.

Checked values

A predicate named valid<Name> that takes one value and returns a bool, where the value's type cannot be listed as a plain sum's can (a record, a number, a string, a list, a sum whose variants carry data), names the values it holds of. validGeometry(g: Geometry) names ValidGeometry, a brand in gen/<name>.ts: Checked<"<module>.validGeometry", Geometry> of gen/_machine.ts. It is still a Geometry to code that wants one, and read-only (a list apart), but no Geometry passes for it. Two things alone make one: the generated validGeometry, a type guard (g is ValidGeometry), and Schemas.ValidGeometry of the adapter, which decodes a fresh Geometry and refuses one the predicate does not hold of. Code that must not take an unchecked value asks for the brand, as a service whose terminal must not be resized beyond what it shows asks for a ValidGeometry, and then cannot skip the spec's own predicate:

declare function resize(session: string, to: ValidGeometry): void
if (validGeometry(wanted)) resize(session, wanted) // resize(session, wanted) alone does not compile

On a plain sum the predicate's subset says the same in variants (isOpen above). A spec that already names something Valid<Name> is refused, as is a type named Checked. The lint (machine/casts) refuses an as, or a type guard, that names such a type outside gen/, as a generated module or the runtime exports it or by another name the file gives it; where the file has the program's types, it also refuses one to a type that holds a check in a field. The predicate is checked when it runs, never proved of the program: what the brand adds is that no path to it skips the predicate, but for any and a merge TypeScript types as an intersection: Object.assign({}, g, { cols: 0 }), or a generic <A, B>(a: A, b: B) => ({ ...a, ...b }), keeps the brand of what it copied, as it keeps a proof's, and neither the compiler nor the lint sees it. The values a predicate rarely holds of are seldom drawn at random, so the generated property tests draw none for its Schema, which is the type's own tested Schema and the predicate.

Kinds and instances

A kind is an abstraction an application defines once, such as a route of its HTTP interface or an action of its agent, together with what every use of it must get right about the machine it drives. An instance is one use of it. Both live in specs, so they are type-checked, reviewed and cited like any rule, and gen checks every instance against its kind before it generates anything.

Where What Example
spec/kinds/<kind>.md, or the tools' std/kinds/<kind>.md the kind: a library spec with a record type and its rules vibestack/std/kinds/endpoint.md: a route's method (Get, Post, Put, Patch or Delete) and path, where a Get drives no step and has no sender, and each other method drives one
the spec of the machine it binds, under a rule of its own the instance: pure val <name>: <Type> = { …, machine: reflected }, after import <kind>.* from "./kinds/<kind>" holdRoute in vibestack/examples/order/spec/index.md
src/kinds/<kind>.vibe the kind's lowering: the one function that turns an instance into what the program runs route() in vibestack/examples/order/src/kinds/endpoint.vibe

A kind's rules are named as the other rules are, by what they do:

Rule Is
pure def wf<Rule>(x: K): Set[…] what is wrong with one instance, as a set of problems; empty where there is none. A bool is allowed, true where it holds
pure def wfAll<Rule>(xs: List[K]): Set[…] what is wrong with every instance declaration of K in the project taken together, including declarations with equal values
pure def derived<Name>(x: K): T a field gen adds to each instance, name, computed from it

std/machine.md says what a machine is to a kind. An instance names its own machine as reflected, which gen writes for the spec that holds it:

type MachineRef = { spec: str, steps: Set[str], senders: Set[str], admits: Set[(str, str)] }
type Binding = Step(str) | Unmodeled(str)

steps holds a name for each transition, senders one for each variant of the sender type, and admits each pair of a step and a sender its guard can admit, as admits in gen/<name>.ts lists them (Proofs, receipts and senders). senderName(Staff) is "Staff". Binding is for a kind whose instances name what they do: a step of the machine, or something the spec does not model, with why, which is a debt the program files as one (fileDebt).

  • A kind is not translated. Quint evaluates its rules on the instances, so a kind may use Quint a spec may not, such as tuples and sets of records. A kind is never simulated or proved, and nothing of it is generated but its module beside the specs that import it.
  • An instance is checked, then generated. Gen writes gen/<name>.reflect.qnt: each instance on its own line of the spec, beside reflected and senderName. It type-checks that module and evaluates every rule of every instance, then every wfAll rule on the project's instances. A problem fails the model stage at the instance's line, with the rule, its heading and its line in the kind: spec/index.md:339: holdRoute breaks wfSenderAdmitted, "An endpoint's sender is one its step's guard admits, or none where it is a GET or its machine names no sender" (std/kinds/endpoint.md:31): ("hold", "Shopper"). Nothing of that spec is then written, and its last modules stay.
  • A guard the table cannot read is refused. An instance that names a step whose guard says something of by together with the state or another parameter (by == Owner or o.open) fails, since admits cannot then say who the step admits and no rule on it can be trusted. Write what depends on by alone as a conjunct of its own.
  • What the program reads. gen/<name>.ts exports each valid instance as a constant, of an interface named after it (holdRoute: HoldRoute) whose fields are its values exactly, with the fields its kind derives and, of its machine, its name alone; and instances, every instance of the spec by its type's name (instances.Endpoint). The Effect adapter exports each bound for the kind's lowering, as Bound<HoldRoute, Input, Event, "index"> of gen/_machine.ts: the instance, the Schema of a type the spec names <Name>Input (HoldRouteInput) where it declares one, its machine's events, and receipt(effect, proof) and debt(effect), which are fileReceipt and fileDebt of the package whose gen/ exports it, for that machine. A lowering in another package, which may not import that package's runtime, files that package's receipts through them: it takes the bound by its shape, never naming another package's Receipt, and the receipts as what receipt and debt return, so that a receipt written as a plain object, filed from another machine's proof or by another package's runtime does not fit. Bound<I, In, Ev>, with any machine's name, still takes the bounds of its own package.
  • Review. An instance relies on every rule of its kind, so a change to any of them re-opens the review of every instance of it, as model changed through it. A kind from std/ is never reviewed itself.
  • Names. Quint reserves List, action and module; each machine's adapter reserves Machine and machine, so a kind names its own reference to one otherwise (MachineRef). No spec may bind reflected, senderName or instances, which gen writes beside instances.
  • A kind of the tools, or the project's own. import endpoint.* from "./kinds/endpoint" takes spec/kinds/endpoint.md where the project has one, else the tools' std/kinds/endpoint.md. A kind a second application needs moves there; each application still writes its own lowering.

Refinement

A spec refines a machine it imports under a name by defining refines<Alias>, which maps its state onto that machine's (vibestack/fixtures/switch.md refines lamp.md in the vibestack repository):

import lamp as L from "./lamp"
pure def refinesL(s: Switch): L::Lamp = { mode: if (s.lit) L::On else L::Off, flips: s.presses }
  • refinesL(initial) must be L::initial.
  • Every transition must either leave refinesL of the state unchanged, or be the transition of L with the same name, allowed by its guard, on refinesL of the state before. That transition's parameters are taken from this one's by name, as a guard's are. A transition that L has no namesake for must leave refinesL unchanged.
  • Simulation checks both on every step, and each is an obligation of the proof. Every reachable state then maps onto a reachable state of L, so every rule of L holds of refinesL of it, as far as L's own unit proved it: the proof line lists what of L is simulated only.
  • A spec refines at most one machine, whose state holds no set.

Supported Quint

In a spec In TypeScript Notes
int, bool, str number, boolean, string Integer literals must fit in 2^53
records interfaces Nest as deep as you like
type Status = Draft | Paid "Draft" | "Paid"
type Parcel = Packed({ weight: int }) | Lost { tag: "Packed"; weight: number } | { tag: "Lost" } Read with match p { | Packed(x) => … | _ => … }
List[T] T[] List(…), append, concat, length, nth, nthOr, removeAt, head, tail, select, foldl, and every, some, includes, listMap
Set[T] of simple values T[] that never holds a value twice Set(…), union, intersect, exclude, filter, map, forall, exists, contains, in, subseteq, size
K -> T Record<K, T> Keys are integers, strings or plain variants; Map(), put, get, getOr, m.keys().contains(k)

Also: + - * / %, comparisons, and or not implies iff, if … else, record construction, spread update and field access, calls to your own definitions, and val bindings at the top of a definition. Anything else stops the model stage with the name of the construct.

  • == and includes compare records, lists, maps and variants by structure. A value holding a set cannot use structural equality; compare sets with subseteq in both directions.
  • Generated arithmetic refuses an integer result outside the safe range. It throws RangeError rather than returning a rounded JavaScript number.
  • xs.nthOr(i, fallback) and m.getOr(k, fallback) are total lookups. xs.removeAt(i) removes one position, or leaves the list unchanged when the position is outside it.
  • Guard every partial operation in the definition that uses it. An index outside a list, a missing map key and a zero divisor stop the simulator and cannot be proved safe; in the generated code one throws a RangeError. Test first and give a default, as problemAt does in the tracker example. For a map the form is exactly if (m.keys().contains(k)) m.get(k) else 0.
  • / and % go towards zero, as in Quint: -7 / 2 is -3 and -7 % 2 is -1. The generated TypeScript and the proofs agree.
  • There are no loops and no recursion. To repeat something until done, fold over a list that is long enough, as ancestors does in the tracker example. What needs a real loop is written by hand in src/ and proved there.
  • A set holds simple values only, and Set(a, b) with members that are not literals is refused, because the two could be equal: write Set(a).union(Set(b)). Use a set when duplicates are impossible in the real thing and a list when they are not.
  • A map is a lookup table. It cannot be listed or iterated; keep a list of keys beside it, or use a list of records with a key field. An event cannot carry one. In the generated state a string key carries a $ in front, so that no key can collide with a property every JavaScript object has.
  • In a match arm, use the fields of what the variant carries (x.weight), or rebuild the variant (Packed({ ...x, weight: 2 })). The carried value cannot be passed on whole. match must be on a name.
  • every, some, includes and listMap are not Quint. They are rewritten into foldl before Quint reads the spec, because Quint evaluates a definition that takes a lambda wrongly when it is used inside its own argument. In TypeScript they are the array methods, except that every, a set's forall and subseteq are written !xs.some(x => !…): the proof then sees each as a quantifier over the members (!(exists x :: x in xs && !…)), as it sees some and includes.
  • The simulator tries small values: integers −1…6, both booleans, three strings, every variant of a plain sum type, and short lists and sets of those. Define <param>Values to choose, which a record or a variant that carries data needs. The sets of an imported spec apply too; the spec's own win.

Writing good rules

  • always rules alone are satisfied by a system that does nothing. Add a sometimes rule for each kind of state a story is meant to make possible.
  • A guard that never allows its event makes it impossible, and every rule then holds of it trivially. check fails when no simulated state allows one. It also lists guards it never saw refuse their event: such a guard often only restates an always rule, which is fine when it protects enabled from outside input, or refuses only beyond the simulator's 20 events.
  • always rules must hold inductively: from any state that satisfies all of them, every transition must lead to a state that satisfies all of them. If simulation passes but proof fails on a transition, a fact about which states are reachable is unstated. In the order example, "Drafts and cancelled orders hold no money" is such a fact: delete it and no simulated trace fails, but submit can no longer be proved to leave a balance.
  • Keep simulation bounds out of guards. A guard such as "stop after day 6" ends up in the generated code. Bound the simulator with <param>Values.
  • Compute something once with a val when a rule uses it several times; repeated folds are what make simulation slow.

Liveness

A leadsTo rule says something happens, not only that nothing bad does: leadsToPaid(o, later) = o.status == Pending implies later.status == Paid. Its runs are the simulated traces of the always stage, each continued for ever in one of two ways: it stops at a state, or it returns to a state it had reached before and repeats the loop. Either is fair unless it puts off a fair event: one declared fair_<event>, "weak" if the event's guard allows it in every state of the loop (or in the state it stops at), "strong" if in any. A fair run breaks the rule when some state on it is followed by none the rule relates it to, and always fails with that run, the state marked.

  • Without a fair_ declaration nothing has to happen, so a run may stop anywhere: declare fair the events the property waits on, the system's own steps and the deliveries the environment promises, and no others.
  • An event lost and sent again forever loops; only "strong" fairness of the delivery rules that out (vibestack/fixtures/ping.md).
  • "Allows" is for the values the simulator tries (<param>Values).
  • within_<rule> = n also asks that the rule be met within n events of any state, whatever events they are: a run that takes n without meeting it breaks the rule, fair or not. Events of the environment count too, so a bound holds only where nothing can delay the answer without limit.
  • A loop needs a state reached twice. A counter that only grows rules loops out, and then only runs that stop are checked: the stage says how many loops it found. Nothing proves a leadsTo rule.

Review

spec/lock.json holds a fingerprint of everything reconciled; review lists what differs. Each status, and what it asks of the agent, is in the sync skill.

Who records it is the project's signOff setting (README, Configuration). Off, the default, every check records what moved once nothing else fails, and lists it, in full, under review as passing rows: the diff of spec/lock.json and of the specs is the record. On, each item fails review until a person reads it and runs pnpm accept, which checks again before it records anything, running only what changed since the last check; without it, pnpm accept only says that the check records the review. check --frozen, for CI to run, records nothing: every item a check would record, an obsolete proof exception it would drop, and any other change it would make to spec/lock.json fails review instead, so the ledger on the branch is the one its author's check wrote.

What Recorded in, under Fingerprint of
document spec/lock.json, specs[<path>]["@document"] title, introduction and links before the first story, whitespace collapsed
story spec/lock.json, specs[<path>]["## <title>"] its text, whitespace collapsed
rule spec/lock.json, specs[<path>][<story> / <heading>] 1. its prose, whitespace collapsed
2. its Quint
3. the Quint of every rule it relies on
contract spec/lock.json, contracts["src/<path>.ts"], or contracts["apps/<name>/src/<path>.ts"] in an owner its //@ lines and the declarations they belong to
flowchart LR
  A["rule A"] -- "mentions Order" --> B["rule B<br/>defines Order"]
  B -- "mentions Status" --> C["rule C<br/>defines Status"]
Loading

A rule relies on every rule whose Quint defines a name (definition, type or variant) that its own Quint mentions, transitively and across imports. Above, editing C's Quint makes A and B model changed through Status (…C); a rule in another spec is named spec/<file>: <rule>. A renamed heading is one rule removed and one new.

The versioned spec/lock.json holds specs keyed by source path, contracts keyed by source file, and unproved keyed by proof unit. Commit it with the specs.

When an accepted simulated-only obligation proves or is removed, review lists its obsolete exception. Recording the spec and contract reviews removes obsolete exceptions. Only pnpm accept unproved can add exceptions, with sign-off or without.

Removed spec paths stay in review until their removal is recorded.

The review is recorded whole or not at all: only when every other stage passes, every story has a rule, every rule has Quint, and no source changed while the check ran.

Using the generated code

gen/<name>.ts exports your types, constants and functions under the names you gave them, and for a state machine:

type Event = { type: "addItem"; qty: number } | { type: "submit" } | …
function parseEvent(x: unknown): Event | undefined   // an untrusted value as an event, or not
function parseState(x: unknown): Order | undefined   // an untrusted value as a state that satisfies inv, or not
function enabled(current: Order, event: Event): boolean  // do the rules allow event now?
function step(current: Order, event: Event): Order       // apply event; unchanged if not allowed; { state, out } with output
function inv(current: Order): boolean                    // every always-rule at once

Every definition from the spec carries a doc comment naming its rule and spec line.

  • Import with the .ts extension, as Node requires: import { type Event, enabled, step } from "../gen/index.ts";

  • Pass everything that arrives from outside through parseEvent or parseState. The proofs assume whole numbers and plain data.

    Accepts Extra fields
    parseEvent safe integers, sets without duplicates dropped
    parseState the state's exact shape, safe integers, sets without duplicates, and inv holds refused

    Both return a fresh copy, so nothing the caller keeps can change it afterwards.

  • Calling a transition directly (pay(o, 5)) is only meaningful when its guard holds. Application code goes through apply, or a Machine in memory (machine()), kept in a store (stored(key)) or kept by the shell (machineOver(load, keep)), of the Effect adapter gen/<name>.effect.vibe, which use enabled and step; a React component goes through useMachine or useMachineSelector of gen/<name>.react.ts (shell skill).

  • gen/ is rebuilt by pnpm gen and pnpm check, and by pnpm install when every spec is valid.

Proofs, receipts and senders

The Effect adapter of a state machine says three things step cannot, in types that gen/_machine.ts declares and no other module can write down. Generation copies vibestack's machine.ts into each package's gen/ as _machine.ts; the adapters import it as ./_machine.ts, and the package's own code from its own gen/ by relative path (../gen/_machine.ts), so a package imports no other package for it and publishes it with its gen/:

Type Says Made only by
Accepted<"<module>", E> the machine accepted the event E: its guard allowed it and its transition ran apply, send and receive of gen/<name>.effect.vibe, which return the new state as that proof
Receipt<"<module>", Effect, Step> an effect happened, for the accepted event of the transition Step, which it carries; or, with Step null, for an effect the spec does not model, which is a debt fileReceipt(module, effect, proof); fileDebt(module, effect)
Sender<By> who sent an event, a value of the spec's sender type, as the host's sign-in established it authenticated(by), in a module named *.auth.ts or *.auth.vibe

<module> is the generated module's name: index, billing__payments.

  • A proof is the state send returned, that very object. send is generic in the event, so send({ type: "hold" }, by) returns an Order & Accepted<"index", { type: "hold" }>: still an Order to code that wants one. fileReceipt("index", "notice", held) then has the type Receipt<"index", "notice", "hold">, and a function that wants the receipt of pay refuses it. A copy of a proof, by a spread or through JSON, is not the proof and does not have its type; where a cast gives it one, fileReceipt throws on it. fileReceipt names its machine first, and takes no other machine's proof.
  • A state that is a number, a boolean or a string carries no proof, and comes back as it is. Keep the state in a record where a receipt is wanted.
  • A sender is made in one place. apply, send and receive take the sender as Sender<…>, which only authenticated returns: call it in one module, named *.auth.ts or *.auth.vibe, from a session, a token or the service an event came through, never from what the caller sent. Review reads that module to see how the program knows who is asking. parseSender and decodeSender return the bare sender type, for replaying a stored log through step; what they return is not a Sender.
  • A sender is one the guard can admit. Where the sender type is a plain sum, gen/<name>.ts exports admits: for each transition, the senders that its guard's conditions on by alone do not refuse, read off the guard's top-level and. canHold(o, by) = by == Staff and o.status == Pending gives hold: ["Staff"], and send({ type: "hold" }, by) then takes a Sender<"Staff"> and no other. A condition that also reads the state or another parameter, such as by == Owner or o.open, refuses nobody in the table, since some state may satisfy it: admits says who can never send an event, and enabled still decides who may now. A sender known only when the program runs, read from a session or a stored log, is one of any, and goes with its event through receive, which takes every signed-in sender. Write what depends on the sender alone as its own conjunct, or as a definition of by alone (mayDrive(by) and …), for the table to see it. SentBy<Event, typeof admits, "Person"> of gen/_machine.ts is the events one sender can send, and Bare<…> the names of those that carry nothing more.
  • The lint holds what types cannot. vibestackConfig of vibestack/eslint, or machineRules(files) in a config written by hand, refuses an import of prove outside gen/ (machine/proofs), an import of authenticated outside a *.auth.* module (machine/senders), an as to a proof, a receipt, a sender, a secret or a check (machine/casts, which also holds secrets to Secrets and checks to Checked values), a declassifyTo… function outside a *.egress.* module or its result anywhere but its sink (machine/egress, Secrets), and parseSender or decodeSender on what a request carried, read by the names request, req, body, payload, params, query, headers, form and input and by .json(), .formData() and .text() (machine/requests).
  • Traces compare receipts. A driver that reports the receipts its shell filed has each compared with the event the spec accepted, and, where its options say so, every accepted event of a transition made to file its receipts (Receipts in traces).
  • A proof or a sender belongs to its package. Each package's copy of the runtime is its own, so a proof or a sender made through one package's gen/ does not fit another's types, and fileReceipt throws on another's proof. The lint refuses an import of a _machine.ts from any gen/ but the importing package's own (machine/own), under any spelling of it. A kind's lowering in another package files through the instance's Bound (Kinds and instances).
  • Schemas.<Type> of the adapter is an Effect Schema for each type the spec declares and for Event, typed by the generated type: what the parsers accept of a value of that type, to decode, encode or generate one without restating it. A state must also satisfy every always rule, which only decodeState checks. The tests of the package whose area the spec is run a generated property test of each, its owner's or the root's for a spec of no owner; another package's copy of the adapter, as the root's of an owner's, is not tested again (CONTRIBUTING.md).

Conformance

The traces stage runs the real application against each state machine's spec, in the package whose code it is, with the events the simulator found. gen/<name>.ts is the oracle; the application is reached three ways:

Is Runs
test/drivers/<name>.ts exports driver and, if it chooses, options, typed by gen/<name>.conformance.ts; imports gen/ as types only in a Node of its own that runs VibeLang: the saved counterexamples, a journey to each sometimes rule, deterministic model-based paths covering reachable modes and accepted/refused transitions, malformed inputs, then random walks
test/traces/<name>.jsonl recorded lines: {state} starts, {event, by?, state?, out?, receipts?} steps; at least one state observed compared line by line
driver:<name> script a program, in any language, that answers each {} (reset) or {event, by?} line with one {state, out?, receipts?} line on deterministic model-based paths and the simulated traces

<name> is the module's name in the root's gen/, and the paths are the package's own: an owner of spec/app/cart.md writes test/drivers/app__cart.ts on gen/app__cart.conformance.ts, records test/traces/app__cart.jsonl or names its script driver:app__cart, all in apps/app. vibestack/examples/order/test/drivers/index.ts is a worked driver; effectDriver from vibestack/testing builds one from a Layer. Run conformance standalone with pnpm exec spec conformance [<module>] [--nightly].

A Driver has reset, dispatch (sends an event through the application's own entry point and returns "accepted" or "refused"), observe, for a spec that emits effects, observeOutput, and, for a shell that files receipts, observeReceipts (the receipts it filed for the event it was last sent, below). With receive(key, raw, by?), which sends an untrusted value through the decoding dispatch skips, the check also sends each kind of event with an unknown type, a field of 1.5 or 2^53, or a field missing, each of which must be refused and change nothing; and with an extra field and fields that change when read again, which must do what the clean event does. options are view (what of the state observe shows), keys (the entities walks interleave), walks (at most this many; 0 for a slow driver, which still runs the journeys and deterministic model-based paths), steps, paths ("transitions" by default, "shortest", "simple", or false to skip generated model paths) and stateKey (an optional state abstraction for path planning) and receipts (for a transition, the effects whose receipts each event of it the spec accepts files, below). The walks use the fixed normal or nightly profile (budgets). The passing summary reports how many transitions the real application accepted and refused.

  • A disagreement is saved. A journey or walk that disagrees is shrunk and written to test/counterexamples/<name>/<hash>.json, which every later run replays first. Decide which side is wrong, fix it, and commit the file: it is a regression test. A saved trace with an event the spec no longer has fails with "the spec has outgrown" it: bring it up to date, or delete it.
  • A shell that keeps state gets a driver. When the package's src/ imports apply from gen/<name>.effect.vibe, it keeps the machine's state itself, and check writes a test/drivers/<name>.ts that fails until its reset, dispatch and observe are filled in. It never replaces a driver. A shell on the generated machine() needs none.

Receipts in traces

A receipt says an effect happened for an event the machine accepted, and carries that event (Proofs, receipts and senders); traces compares the receipts the application files with what the spec did with each event it was sent. A driver's observeReceipts(key) returns what fileReceipt and fileDebt made for the last dispatch or receive for key, and a recorded line or a driver: program's answer may carry them as receipts. Each must be of the machine checked, and either a debt or the receipt of the event just sent, which the spec accepted: a receipt for an event the spec refuses, from the proof of an earlier event unlike this one (a receipt carries the event, not when it was sent), or of another machine departs from the spec. Where a driver's options.receipts names the effects of a transition, as { hold: ["notice"] }, every event of it the spec accepts files exactly those receipts, once each, so a mutating path that files none, or files one twice, departs too; the names of options.receipts are the spec's transitions, which the compiler and the check hold them to. A debt is never compared with the spec, which does not model it, and what a receipt claims happened in the world, as an email sent, is the application's word.

Exploring the page

The explore stage drives a package's page in a real browser with Bombadil: it clicks, types, scrolls and reloads at random, and checks properties in every state it reaches. A package has a page when it has an index.html at its top or under src/.

  • Served by the package itself. check runs its start script, or dev when that is not the studio, and explores the first http://localhost or 127.0.0.1 address it prints within 300 s. A page with neither script fails.
  • In Chromium. Playwright's Chromium (pnpm exec vibestack doctor --install installs it), or the browser CHROME names. Bombadil runs on Linux x64 and arm64 and on Apple silicon; elsewhere the stage prints a - line and CI explores the page.
  • For a fixed time, from no seed. The fixed profile's seconds, Chrome's start included (budgets). The actions are random, so two runs explore differently.
  • test/bombadil.ts says what must hold. It is an ES module Bombadil bundles itself. Re-export @antithesishq/bombadil/browser/defaults (no uncaught exception or unhandled rejection, no console error, no HTTP error), and export a property for each rule the page must keep, citing it as a test does. The types come from @antithesishq/bombadil, which vibestack init adds. Without the file, the defaults are checked. apps/app/test/bombadil.ts is a worked one. Run exploration standalone with pnpm exec spec explore [--nightly].
  • A broken property is saved. The run is kept in test/__traces__/bombadil, which is not committed; pnpm exec bombadil browser inspect test/__traces__/bombadil shows each state. Later runs replay it first: one that still breaks fails, one that cannot run keeps it, and one that breaks nothing or no longer applies to the page removes it. A bug worth keeping fixed becomes a step of the journey it broke.
  • A pass is remembered until what the page reads changes, or the installed Bombadil and the packages it loads, or the script: the package's files but its tests and their configuration, drivers, traces, counterexamples, contracts, proofs and spec/; each file and directory its code or scripts name by a path, inside the project or a workspace package the page reads; what each workspace package its code imports, or its scripts run, exports, or, where it exports nothing, what it holds that git does not ignore or that its code names; and the generated modules it imports, or all of them where its code names none. A page that runs the tools, as Studio's does, reads the code of them all. The nightly check always explores afresh.

Large applications

  • One spec per area, each a few hundred lines: a state machine for each thing that has a life cycle, libraries for what they share, and machines that import machines where rules span them. check runs them in dependency order and proves each against the definitions of what it imports, not their proofs, so the cost of a proof grows with the spec, not with everything beneath it. Its proof file may call what their units proved.
  • One tree for every package. Each application or shared package keeps its specs in spec/<its name>/ and its code in its own directory; the root's check covers them all (One spec tree).
  • Only what changed is checked again. Each run of Quint is kept in .spec-cache/ under what it reads, the Quint of the spec and of everything it imports without its prose, comments and layout, and the Quint installed, so a change to the prose or to the tools that leaves the Quint alone runs no Quint again. A typecheck is kept under the spec's own Quint and only the signature of each spec it imports: its declarations without their bodies, with the types and effects Quint inferred for them. An edit inside a body that leaves the signature alone typechecks only the spec edited, and every spec that imports it is still simulated and proved again. Each run of Dafny on a proof, likewise, under the Dafny it checks and the Dafny and Z3 installed. Each simulation result, a failing one too (its seed is fixed), and each passing proof result is kept beside them, under a fingerprint of the spec's Quint without its comments, everything it imports and the versions of the tools that compute it, so a change to the tools reruns only the stages that run the changed code. A passing typecheck is kept under what the compiler read: the package's files but its Markdown and Quint, its tsconfig.json and the configurations it extends, every file outside node_modules the compile read, the lock file and the compiler's bytes. A test pass is kept under the files its tests read, which are the package's but its specs' Markdown and their Quint in gen/, the review ledger spec/lock.json, the simulations' traces and the agent and reader prose at its top: a test reads the generated modules, so a prose edit, or a check recording it, runs no test again. A driver's passing run is kept under those files and the events the simulator found; a failure, and a driver: program, run every time. A test or driver run during which those files changed is not kept. The specs are simulated at once.
  • The spec covers the rules, not the plumbing. Chat, HTTP and storage stay hand-written around the generated core, as vibestack/examples/dashboard/src/notify.vibe does for sending messages.

Checking harder

Simulation is seeded from what it simulates and the fixed profile, so a run repeats exactly; exploring the page does not. pnpm all check -- --nightly uses the larger nightly profile, explores each page five times as long, and always checks afresh. A failing always rule or an unreached sometimes goal prints its seed and the pnpm exec quint run command that replays it.

To check a model exhaustively up to a depth with the Apalache model checker (needs Java 17+, downloads Apalache on first use):

pnpm exec quint verify gen/index.run.qnt --main index_run --invariant inv --max-steps 10