@toiroakr/chisel 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/README.md +354 -21
  2. package/dist/absence.d.ts +28 -0
  3. package/dist/absence.js +266 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +26 -19
  6. package/dist/behavior.js +193 -203
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/beside.d.ts +5 -0
  9. package/dist/beside.js +10 -0
  10. package/dist/beside.js.map +1 -1
  11. package/dist/border.d.ts +7 -8
  12. package/dist/border.js +88 -36
  13. package/dist/border.js.map +1 -1
  14. package/dist/bounds.d.ts +1 -0
  15. package/dist/bounds.js +27 -0
  16. package/dist/bounds.js.map +1 -0
  17. package/dist/changes.d.ts +23 -0
  18. package/dist/changes.js +355 -0
  19. package/dist/changes.js.map +1 -0
  20. package/dist/checks.d.ts +1 -0
  21. package/dist/checks.js +295 -0
  22. package/dist/checks.js.map +1 -0
  23. package/dist/cli.d.ts +4 -0
  24. package/dist/cli.js +351 -14
  25. package/dist/cli.js.map +1 -1
  26. package/dist/codec.js +16 -7
  27. package/dist/codec.js.map +1 -1
  28. package/dist/codegen.js +6 -8
  29. package/dist/codegen.js.map +1 -1
  30. package/dist/composition.d.ts +3 -3
  31. package/dist/composition.js +9 -8
  32. package/dist/composition.js.map +1 -1
  33. package/dist/conformance.d.ts +24 -0
  34. package/dist/conformance.js +44 -0
  35. package/dist/conformance.js.map +1 -0
  36. package/dist/data.d.ts +3 -2
  37. package/dist/data.js +7 -3
  38. package/dist/data.js.map +1 -1
  39. package/dist/decimal-js.d.ts +2 -0
  40. package/dist/decimal-js.js +5 -0
  41. package/dist/decimal-js.js.map +1 -0
  42. package/dist/decimal.d.ts +2 -0
  43. package/dist/decimal.js +3 -0
  44. package/dist/decimal.js.map +1 -0
  45. package/dist/dependency.d.ts +9 -6
  46. package/dist/dependency.js +23 -17
  47. package/dist/dependency.js.map +1 -1
  48. package/dist/domain.d.ts +6 -2
  49. package/dist/domain.js +65 -25
  50. package/dist/domain.js.map +1 -1
  51. package/dist/ensures.js +3 -3
  52. package/dist/ensures.js.map +1 -1
  53. package/dist/equal.d.ts +1 -0
  54. package/dist/equal.js +135 -0
  55. package/dist/equal.js.map +1 -0
  56. package/dist/errors.d.ts +18 -0
  57. package/dist/errors.js +25 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/exact.d.ts +13 -1
  60. package/dist/exact.js +52 -3
  61. package/dist/exact.js.map +1 -1
  62. package/dist/feasibility.d.ts +5 -3
  63. package/dist/feasibility.js +309 -53
  64. package/dist/feasibility.js.map +1 -1
  65. package/dist/guard-borders.d.ts +14 -5
  66. package/dist/guard-borders.js +229 -190
  67. package/dist/guard-borders.js.map +1 -1
  68. package/dist/guard-scope.d.ts +65 -0
  69. package/dist/guard-scope.js +384 -0
  70. package/dist/guard-scope.js.map +1 -0
  71. package/dist/hooks.d.ts +22 -0
  72. package/dist/hooks.js +2 -0
  73. package/dist/hooks.js.map +1 -0
  74. package/dist/index.d.ts +30 -8
  75. package/dist/index.js +18 -5
  76. package/dist/index.js.map +1 -1
  77. package/dist/interleave.d.ts +31 -0
  78. package/dist/interleave.js +202 -0
  79. package/dist/interleave.js.map +1 -0
  80. package/dist/interval.d.ts +8 -0
  81. package/dist/interval.js +213 -23
  82. package/dist/interval.js.map +1 -1
  83. package/dist/isolated.d.ts +7 -1
  84. package/dist/isolated.js +53 -5
  85. package/dist/isolated.js.map +1 -1
  86. package/dist/kinds/decimal.d.ts +1 -0
  87. package/dist/kinds/decimal.js +16 -0
  88. package/dist/kinds/decimal.js.map +1 -0
  89. package/dist/kinds/rational.d.ts +1 -0
  90. package/dist/kinds/rational.js +13 -0
  91. package/dist/kinds/rational.js.map +1 -0
  92. package/dist/kinds/temporal.d.ts +1 -0
  93. package/dist/kinds/temporal.js +15 -0
  94. package/dist/kinds/temporal.js.map +1 -0
  95. package/dist/lean/behavior.d.ts +29 -0
  96. package/dist/lean/behavior.js +76 -0
  97. package/dist/lean/behavior.js.map +1 -0
  98. package/dist/lean/given.d.ts +10 -0
  99. package/dist/lean/given.js +15 -0
  100. package/dist/lean/given.js.map +1 -0
  101. package/dist/lean/index.d.ts +11 -0
  102. package/dist/lean/index.js +8 -0
  103. package/dist/lean/index.js.map +1 -0
  104. package/dist/lean/model.d.ts +20 -0
  105. package/dist/lean/model.js +133 -0
  106. package/dist/lean/model.js.map +1 -0
  107. package/dist/lean/protocol.d.ts +14 -0
  108. package/dist/lean/protocol.js +34 -0
  109. package/dist/lean/protocol.js.map +1 -0
  110. package/dist/lean/rule.d.ts +54 -0
  111. package/dist/lean/rule.js +149 -0
  112. package/dist/lean/rule.js.map +1 -0
  113. package/dist/lean/schema.d.ts +46 -0
  114. package/dist/lean/schema.js +155 -0
  115. package/dist/lean/schema.js.map +1 -0
  116. package/dist/machine-check.d.ts +73 -0
  117. package/dist/machine-check.js +215 -0
  118. package/dist/machine-check.js.map +1 -0
  119. package/dist/machine.d.ts +122 -0
  120. package/dist/machine.js +271 -0
  121. package/dist/machine.js.map +1 -0
  122. package/dist/model.d.ts +110 -11
  123. package/dist/model.js +724 -80
  124. package/dist/model.js.map +1 -1
  125. package/dist/off-grid.d.ts +4 -0
  126. package/dist/off-grid.js +92 -0
  127. package/dist/off-grid.js.map +1 -0
  128. package/dist/outcomes.d.ts +15 -0
  129. package/dist/outcomes.js +120 -0
  130. package/dist/outcomes.js.map +1 -0
  131. package/dist/pairs.js +14 -5
  132. package/dist/pairs.js.map +1 -1
  133. package/dist/partition.d.ts +1 -0
  134. package/dist/partition.js +101 -19
  135. package/dist/partition.js.map +1 -1
  136. package/dist/placeholders.d.ts +3 -0
  137. package/dist/placeholders.js +44 -0
  138. package/dist/placeholders.js.map +1 -0
  139. package/dist/proof.d.ts +6 -0
  140. package/dist/proof.js +282 -56
  141. package/dist/proof.js.map +1 -1
  142. package/dist/protocol.d.ts +22 -0
  143. package/dist/protocol.js +12 -0
  144. package/dist/protocol.js.map +1 -0
  145. package/dist/relations.d.ts +30 -0
  146. package/dist/relations.js +235 -0
  147. package/dist/relations.js.map +1 -0
  148. package/dist/replay.d.ts +45 -0
  149. package/dist/replay.js +157 -0
  150. package/dist/replay.js.map +1 -0
  151. package/dist/rewrites.d.ts +41 -0
  152. package/dist/rewrites.js +180 -0
  153. package/dist/rewrites.js.map +1 -0
  154. package/dist/rule.d.ts +74 -11
  155. package/dist/rule.js +429 -22
  156. package/dist/rule.js.map +1 -1
  157. package/dist/runtime.d.ts +12 -0
  158. package/dist/runtime.js +8 -0
  159. package/dist/runtime.js.map +1 -0
  160. package/dist/schema.d.ts +44 -28
  161. package/dist/schema.js +50 -113
  162. package/dist/schema.js.map +1 -1
  163. package/dist/specification.d.ts +23 -3
  164. package/dist/specification.js +1001 -96
  165. package/dist/specification.js.map +1 -1
  166. package/dist/stops.d.ts +20 -0
  167. package/dist/stops.js +221 -0
  168. package/dist/stops.js.map +1 -0
  169. package/dist/temporal-global.d.ts +4 -0
  170. package/dist/temporal-global.js +11 -0
  171. package/dist/temporal-global.js.map +1 -0
  172. package/dist/temporal.d.ts +22 -0
  173. package/dist/temporal.js +113 -0
  174. package/dist/temporal.js.map +1 -0
  175. package/dist/tla-validate.d.ts +31 -0
  176. package/dist/tla-validate.js +151 -0
  177. package/dist/tla-validate.js.map +1 -0
  178. package/dist/tla.d.ts +61 -0
  179. package/dist/tla.js +722 -0
  180. package/dist/tla.js.map +1 -0
  181. package/dist/verification.d.ts +9 -0
  182. package/dist/verification.js +7 -0
  183. package/dist/verification.js.map +1 -0
  184. package/dist/ways.d.ts +11 -5
  185. package/dist/ways.js +51 -45
  186. package/dist/ways.js.map +1 -1
  187. package/dist/world.d.ts +98 -0
  188. package/dist/world.js +463 -0
  189. package/dist/world.js.map +1 -0
  190. package/package.json +49 -10
  191. package/schema/report.schema.json +169 -1
package/README.md CHANGED
@@ -1,28 +1,68 @@
1
1
  # Chisel
2
2
 
3
- Chisel is an experimental TypeScript toolkit for growing an executable business specification from a closed data model, generated examples, and human-provided expectations.
3
+ Chisel is an experimental TypeScript toolkit for defining executable state transitions and checking the same definitions against invariants. A machine runs in production through `@toiroakr/chisel/runtime`; its verification properties live separately in `@toiroakr/chisel/verification`, so they are not part of the runtime import graph. See [one reducer for runtime and exhaustive checking](#one-reducer-for-runtime-and-exhaustive-checking) for a complete example.
4
4
 
5
- The workflow is deliberately ordered:
5
+ The machine workflow is:
6
6
 
7
7
  ```text
8
- declare data and behavior
9
- → generate unanswered examples
10
- → let a human fill expected results
11
- → refine data and behavior
12
- → implement an executable model
13
- → check the model against the examples
8
+ define state and commands
9
+ → implement one transition expression
10
+ → run it with runMachine
11
+ → declare invariants in a separate specification
12
+ → check reachable states or generate TLA+ proof obligations
14
13
  ```
15
14
 
16
- Install with `npm install @toiroakr/chisel` (Node.js 26 or newer).
15
+ Install with `npm install @toiroakr/chisel` (Node.js 22.22, 24.15, 26 or newer, or Bun).
16
+
17
+ **Entry points.** The package root `@toiroakr/chisel` is a small runtime written with functions (`c.string()`, `c.lte(a, b)`, `c.model(...)`), kept small so a bundle holds only the functions it calls. Everything else is a sub-path:
18
+
19
+ | Import | What it is | When to use it |
20
+ | --- | --- | --- |
21
+ | `@toiroakr/chisel` | the function-based runtime: schemas, rules, `model`, `behavior`, `implement`, `perform`, `performSync` | production code that decides and validates |
22
+ | `@toiroakr/chisel/full` | the method-based library with `check`, `generate`, `verify`, `test`, decimals, Temporal, dependencies and codecs | specifications and tests; it also takes declarations made with the root |
23
+ | `@toiroakr/chisel/runtime` | the method-based runtime of 0.2.x: machines, decimals, Temporal, dependencies, `decode`/`encode` | production code that needs what the root lacks |
24
+ | `@toiroakr/chisel/verification` | machine invariants, `checkMachine`, TLA+ translation | verification modules, outside the production graph |
25
+ | `@toiroakr/chisel/decimal` | side-effect import that loads decimal.js and lets the root compare `Decimal` values | production code holding decimals |
26
+ | `@toiroakr/chisel/temporal` | side-effect import that lets the root compare Temporal values (`Instant`, `PlainDate`, `PlainTime`, `PlainDateTime`, `PlainYearMonth`, `ZonedDateTime`, `Duration`); it needs no `Temporal` global until a value exists | production code holding Temporal values |
27
+ | `@toiroakr/chisel/checks` | side-effect import that runs the declaration checks | a test setup file, so a bad declaration still throws where it is written |
28
+ | `@toiroakr/chisel/isolated` | `runIsolated`, which needs Node | hosts running the CLI's worker boundary |
29
+
30
+ **Migration to this version (breaking):** the root used to be the method-based runtime. Move code that used it to `@toiroakr/chisel/runtime` unchanged, or rewrite it with functions: `v.$gt(x)` becomes `c.gt(v, x)`, `c.string().min(1)` becomes `c.pipe(c.string(), c.minLength(1))`, `x.optional()` becomes `c.optional(x)` and `list.$all(f)` becomes `c.all(list, f)`. Imports of `check`, `generate`, `spec` and the other analyses stay at `@toiroakr/chisel/full`; machine verification stays at `@toiroakr/chisel/verification`. decimal.js and the declaration checks are no longer loaded by the root or `/runtime` until `/decimal`, `/checks`, `/full`, `/verification` or the CLI is loaded.
31
+
32
+ **What the root compares.** Numbers, bigints, strings (as NFC, in code point order), `Date`s, and plain objects and arrays (by structure for `eq`/`ne`). It does not guess about any other class instance: `c.lt(decimal, other)` on a `Decimal` or a Temporal value throws `Cannot order Decimal against Decimal: register their type with registerKind, or import @toiroakr/chisel/decimal or @toiroakr/chisel/temporal` until the type is registered. `import "@toiroakr/chisel/decimal"` registers `Decimal`, `import "@toiroakr/chisel/temporal"` registers the Temporal types, and `/full` registers both and `Rational`. Another type is registered with `c.registerKind({ name, is, order, same })`: `is(value)` says whether a value is of the type (a precise test, not "has a `comparedTo` method"), `order(a, b)` answers a negative number, zero or a positive number, and `same(a, b)` answers whether they are equal. The first registration whose `is` accepts either side is used, and a second registration under one `name` replaces the first, so loading a module twice is harmless.
33
+
34
+ The earlier behavior-and-example workflow remains available from `/full` and is documented below.
17
35
 
18
36
  ## 1. Declare data and behavior
19
37
 
20
- The examples import Chisel as a namespace, `import * as c from "@toiroakr/chisel"`, the way zod and valibot are used as `z` and `v`; the names below are written without the prefix.
38
+ The behavior and specification examples below use `import * as c from "@toiroakr/chisel/full"`, the method-based library (`c.string().min(1)`, `input.next.$gt(input.current)`). The package root `@toiroakr/chisel` is a small runtime written with functions, so a bundle holds only the functions it calls:
39
+
40
+ ```ts
41
+ import * as c from "@toiroakr/chisel";
42
+
43
+ const expiry = c.behavior("expiry", {
44
+ input: c.variants("state", { recorded: c.object({ expiresAt: c.jsDate(), now: c.jsDate(), name: c.pipe(c.string(), c.minLength(1)) }) }),
45
+ result: c.variants("verdict", { candidate: c.object({ name: c.string() }), keep: c.object({}) }),
46
+ effects: c.variants("kind", {}),
47
+ ensures: clause => [clause.when("candidate only when expired", ["candidate"], input => c.lte(input.expiresAt, input.now))],
48
+ });
49
+
50
+ const decide = c.implement(expiry, { cases: { recorded: c.model("decide", input => ({
51
+ result: c.choose(c.lte(input.expiresAt, input.now), { verdict: "candidate" as const, name: input.name }, { verdict: "keep" as const }),
52
+ effects: [],
53
+ })) } });
54
+
55
+ c.performSync(decide, { state: "recorded", expiresAt: new Date(1), now: new Date(2), name: "a" });
56
+ ```
57
+
58
+ The root has the schemas `string`, `rawString`, `jsDate`, `boolean`, `number`, `int`, `literal`, `enum`, `optional`, `object`, `variants`, `array`, `record` and `pipe` (with `check`, `min`, `max`, `minLength`, `maxLength`), the rules `lt`, `lte`, `gt`, `gte`, `eq`, `ne`, `and`, `or`, `not`, `all`, `any` and `length`, the model nodes `model`, `choose`, `bind`, `map`, `fold`, `arithmetic` (numbers and bigints) and `concat`, `behavior`, `protocol`, `given`, `implement`, `performSync`, `perform` and `todo`. A declaration made with it carries what `check`, `verify` and `generate` read, so `@toiroakr/chisel/full` takes it as it takes one written with the methods; the same declaration is run in production and proved in a test. A bundle that runs one decision, with the validation of its input and answer and an `ensures` clause, is about 12.7 KB unminified, 7.0 KB minified and 3.0 KB gzipped, and one that also writes a `protocol` and a `c.given` clause about 16.3 KB, 9.2 KB and 3.8 KB, since a bundle holds only what a declaration calls (`test/lean-size.test.ts` holds both). Decimals, rationals, Temporal values, dependencies and `call`, arithmetic on them, `decode`/`encode` and the state-machine runtime are not in it yet: they stay in the method-based runtime of earlier versions, `@toiroakr/chisel/runtime` (see [one reducer for runtime and exhaustive checking](#one-reducer-for-runtime-and-exhaustive-checking)), which does not load decimal.js (`import "@toiroakr/chisel/decimal"` loads it) or run the declaration checks (`import "@toiroakr/chisel/checks"` runs them, and a test suite imports it once so a bad declaration still throws where it is written: a guard comparing a decimal with a value off its grid, a read of a field that may be left out, a `match` that misses a case, an `ensures` clause or a `refine` rule breaking the same laws, a callback in a model, an `ensures` clause named twice). `placeholder()` of a schema with invariants stays at the value of its kind until `/checks` is imported.
59
+
60
+ `c.performSync(implementation, input, deps)` answers what `perform` answers, for a caller that cannot await: it parses and validates the same way and throws `SpecificationError` where a dependency or a decision answers a promise.
21
61
 
22
62
  The first version describes the domain vocabulary and the behavior boundary, not its implementation. `variants(discriminant, { case: object(...) })` declares a discriminated union: a value is exactly one of the named cases, told apart by the discriminant field (Souther calls this a sum type). An `object` holds exactly the fields it declares: a value carrying another key is refused, not trimmed, so a model answering with a stray field fails `check` instead of passing it.
23
63
 
24
64
  ```ts
25
- import * as c from "@toiroakr/chisel";
65
+ import * as c from "@toiroakr/chisel/full";
26
66
 
27
67
  const Order = c.variants("state", {
28
68
  unpaid: c.object({ orderId: c.string() }),
@@ -173,6 +213,8 @@ export const cancellation = c.spec("order cancellation", {
173
213
  - `data("Price", object(...))` creates a nominal object type. `Price.create(...)` validates and freezes a value. In a model, use `construct(Price, {...})` and list `constructs: [Price]` in `implement`. The ordinary schema parser remains an explicit validation boundary. This is a TypeScript type guarantee, not protection from `any` or malicious host modules.
174
214
  - `int64()` stores signed 64-bit `bigint` values; `rational()` stores reduced `Rational` values. `arithmetic` supports exact bigint, Rational, and Decimal operations; `quotient` returns an exact Rational, including for integer division. `int()` retains safe JavaScript integers and `number()` retains finite JavaScript numbers. Decimal arithmetic in the model and linear rules does not inherit decimal.js's process precision setting. JSON uses strings for int64, Rational, Decimal, and Temporal values.
175
215
  - `string()` now normalizes to NFC, rejects unpaired surrogates, and measures and orders Unicode scalar values. Enum and literal declarations must already be NFC; parsed text is normalized. This changes results for supplementary characters and decomposed text.
216
+ - `jsDate()` carries a JavaScript `Date` and needs no `Temporal`, so it runs on every supported Node.js. `parse` refuses an invalid Date and keeps its own copy, and a Date written in a rule (`v.$gte(new Date(...))`) or a model is copied too, so changing yours later leaves the schema alone. It is ordered by the time it holds with `min`/`max`/`gt`/`lt`, a rule or a guard; borders step by a millisecond; a guard comparing two of them is read on their difference in milliseconds. JSON carries exactly the string `toISOString()` writes (`2026-09-07T12:00:00.000Z`), and `decode` refuses any other, since `new Date("2026-09-07")` and `new Date("2026-09-07T12:00:00")` read in the time zone of the machine. `generate` writes `new Date("…")`, and a rule describes a Date the same way, whatever the time zone.
217
+ - `rawString()` carries a string exactly as written: it neither normalizes to NFC nor refuses an unpaired surrogate, and a recorded answer is compared as written. Rules and models compare text as NFC, so reading one would answer as if it were normalized (`label != "é"` answers false for the decomposed `"e\u0301"`, which is two code points long); a rule, guard, ensures clause or model condition that reads a `rawString`, and `concat` of one, is therefore refused where it is written. Pass it through (`{ label: input.label }`), or compare a `string()` instead. A text constant of a model is kept as written, so a model may answer `"e\u0301"` as a `rawString`. A `string()` answer may be composed into a `rawString` input; the other way is refused, since `string()` would change it.
176
218
 
177
219
  `check` reports `measures.constructions` and `measures.pairs` in schema version 2. Configure pair budgets with `pairs: { obligations, candidates }` or CLI `--pair-obligations` / `--pair-candidates`. Bounds apply to proofs and generation; an unresolved obligation fails strict checking.
178
220
 
@@ -185,7 +227,7 @@ npm run example:verified
185
227
 
186
228
  `verify` exits 1 for either a counterexample or an unproved implementation. Text diagnostics use `file: error CHISEL001: description`, suitable for an editor task's problem matcher. TypeScript provides type errors and completion; [an example VS Code task](docs/editor-task.json) runs semantic verification. This repository's `build` runs the verifier on its complete expression example after TypeScript compilation.
187
229
 
188
- The executable CLI runs all commands in a worker with a default 30-second deadline (including module loading), a 256 MiB old-generation heap limit, and a 1 MiB streamed-output limit. The deadline terminates synchronous loops too. `runIsolated(argv, timeoutMs)` offers this boundary to hosts. Direct in-process `check` / `perform` calls cannot preempt arbitrary JavaScript callbacks; expression evaluation has its own step budget. The worker is a resource boundary, not an I/O sandbox for imported modules.
230
+ The executable CLI runs all commands in a worker with a default 30-second deadline (including module loading), a 256 MiB old-generation heap limit, and a 1 MiB streamed-output limit. The deadline terminates synchronous loops too. `runIsolated(argv, timeoutMs)` from `@toiroakr/chisel/isolated` offers this boundary to hosts. It needs Node, which is why it has an entry of its own: `@toiroakr/chisel/full` imports no Node module, so a bundle of it runs where only Web APIs exist, such as a browser or an edge or serverless function runtime. Direct in-process `check` / `perform` calls cannot preempt arbitrary JavaScript callbacks; expression evaluation has its own step budget. The worker is a resource boundary, not an I/O sandbox for imported modules.
189
231
 
190
232
  The proof system preserves matching quantified facts from input invariants and guards, including nested quantifiers and captured input fields. It also proves structural schema inclusion for collections and pipeline boundaries. Typed `map` and `fold` expressions prove their element and accumulator contracts. Recursive proofs, general higher-order functions, and unsupported substitutions remain unresolved. Full Souther language compatibility is not implied by a passing report; the guarantee applies to the selected model and the reported obligations.
191
233
 
@@ -200,7 +242,7 @@ const pricing = c.behavior("pricing", {
200
242
  }),
201
243
  result: c.int().min(1).max(101),
202
244
  effects: c.variants("kind", {}),
203
- requires: {
245
+ dependencies: {
204
246
  price: c.dependency(c.int().min(1).max(100), c.int().min(0).max(100)),
205
247
  },
206
248
  });
@@ -219,6 +261,8 @@ The verifier proves each argument satisfies the dependency's input contract and
219
261
 
220
262
  At runtime, every call validates its input, output, and applicable `ensures`. Model inputs, value dependencies, and call inputs and outputs are copied and frozen, including Decimal values, to prevent a dependency from mutating values used by another expression. Unsupported host objects such as mutable custom class instances are rejected at this boundary; use plain data or the supported Decimal, Rational, and Temporal types. The proof is conditional on the declared dependency contracts; it does not certify host callback termination or implementation. Case-scoped dependency postconditions supply proof facts when `bind` or `matchValue` establishes the matching result tag. These bindings also expose result fields to expressions and guards. Local and repeated branch coverage remains unmeasured, as described below.
221
263
 
264
+ A function dependency may answer a promise, as one that reads a database or calls another service does: `perform` awaits it where the model calls it and holds the settled answer to the same contract, so `c.perform(implementation, input, { lookup: async id => (await db.find(id)) ?? null })` reads the answer as a value. Calls run one after another, in the order the model reads them, each after the one before has settled; a rejection fails the run with its own error. A model whose dependencies answer values is still evaluated synchronously, so fake tables, `check` and `generate` read it as before. An action's own code (`run`, `orElse`, a `match` handler or a free-form decision) reads a dependency's answer as a value, so a dependency that answers a promise there fails the run with a `SpecificationError` instead of being read as its answer; a dependency that answers a value reaches that code as before, called on the object supplied.
265
+
222
266
  A model can pass the entire input with `c.call(deps.lookup, input)`; internal dependency bindings are excluded. `#deps` is reserved as a top-level input field when a behavior declares dependencies. Existing fake tables work with `call` in example checks.
223
267
 
224
268
  ### Local values and collections
@@ -245,6 +289,20 @@ const result = c.matchValue(answer, c.call(deps.lookup, input), {
245
289
  });
246
290
  ```
247
291
 
292
+ Where the expression is a field of the input declared with that schema, `matchValue` reads the field itself: its cases are measured like a guard on the field's discriminant (arms, ways and borders), and the fields of a case are proved under it, so a model written this way can pass `check --strict`.
293
+
294
+ ### Absence is a case of a sum
295
+
296
+ A comparison reading a value that may be left out is refused where it is written: an optional field (`c.string().optional()`), a field of an object that may be left out, an entry of a record read by its key (`input.tags["owner"]`), a field only some cases of a sum declare, or the constant `undefined`. Such a comparison would hold whenever the value is left out, so `input.note.$eq("urgent")` would silently pass for an input without a note. `refine` throws (`refine reads $.割引額, which may be left out: write its absence as a case of a sum`), and so do `implement` for a guard or a model (`guard in note reads $.note, which may be left out: …`) and `behavior` for an `ensures` clause. Write the absence as a case of a sum instead, and read a case's fields where the case is settled: under an earlier guard or conjunct comparing the discriminant (`input.name.state.$eq("given").$and(input.name.value.$eq("x"))`), inside a `choose` on it, or in the case's body of a `matchValue`. A term of a sum reaches the fields of every case, and `implement` checks which reads are settled. An optional field may still be carried into an answer; only comparing it is refused.
297
+
298
+ ```ts
299
+ const label = c.variants("state", { absent: c.object({}), given: c.object({ value: c.string().min(1) }) });
300
+ const result = c.matchValue(label, input.name, {
301
+ absent: () => ({ verdict: "none" }),
302
+ given: name => ({ verdict: "owner", name: name.value }),
303
+ });
304
+ ```
305
+
248
306
  `map(elementSchema, outputSchema, values, element => body)` proves the body for an arbitrary element. `fold(elementSchema, accumulatorSchema, values, initial, (accumulator, element) => body)` proves that the initial value and every update satisfy the accumulator schema. This is an inductive invariant, independent of the array length:
249
307
 
250
308
  ```ts
@@ -262,12 +320,12 @@ These builders run at declaration time; the interpreter executes the resulting e
262
320
 
263
321
  Locals cannot escape their body. Declare each binding separately rather than reusing its expression in multiple locations. Top-level input names starting with `#local:` are reserved in models. Reading the whole input inside a body excludes local bindings.
264
322
 
265
- Construction proofs and example coverage are separate. `verify` can prove a body with local or iterated branches, but those branches' coverage is currently unmeasured: `check --strict` cannot succeed for such a model. Branch-free collection expressions remain eligible for strict checking. Array-length relationships and arbitrary fold postconditions beyond the declared accumulator contract are not inferred.
323
+ Construction proofs and example coverage are separate. A branch on a dependency's answer (`matchValue` or `choose` over what `c.call` answers) is measured like a guard: the answer is read as a position of its own, written `lookup()` in reports, that may be any value the dependency declares it answers and is held to its `ensures` (a way they leave no value is owed no row). Rows reach such a way through the specification's `fakes`, and `generate` (given `fakes`, as `chisel generate` passes them) offers the input a fake row asks for each way or border point no row reaches yet, or names the answer a fake row must give. A branch on a value the model computes is measured too. A `bind` of a sum or difference of input numbers, a whole multiple of one, a constant or an object of such values is read where it is read (`bind(c.int(), c.arithmetic("add", input.a, input.b), total => c.choose(total.$gte(100), …))` is the guard `$.a + $.b >= 100`, with its border drawn on the input), and a condition that reads no value settles which way it goes. A quotient by a whole number compared with a rational is read multiplied out (`quotient($.a, 7) >= new c.Rational(3n)` is `$.a >= 21`); a rational compared with a plain number, which never holds as the model compares them, is refused by `implement`. This reading is for measurement only: the model runs as it is written, and what a run takes is recorded in the terms the analyses read. A sum of `number` fields is not read as an expression, since the model adds numbers in floating point and an exact expression could answer otherwise (`0.1 + 0.2 == 0.3`). A value Chisel cannot read as an expression (a product of two inputs, a bound `choose`, a concatenation, whose NFC form may be shorter than its parts, a temporal value, a fold's accumulator) is shown by what computes it (`multiply($.a, deps.rate)`), and a way through it, or a border point drawn on it, that no row reaches is settled by running the case's inputs through the decision: the fields the decision's choices turn on, every stand-in of the value dependencies, and every answer a function dependency's contract allows (its output, as the schema the answer is bound under also takes it, and its `ensures`). One that takes the way makes it a gap, and where a fake row gives that answer `generate` offers the input it asks; where those runs are every input, stand-in and answer there is and none takes it, no row is owed (three times a whole price is never 200). Before and after that, a comparison a sum, difference or product can never meet given the bounds of what it reads owes no row (two inputs of at least 2 never multiply to less than 4), and a product of two integer inputs equal to a whole number is tried at every divisor pair of it (a prime is never a product of factors of at least 2; 1000001 is 101 × 9901). Only where none of this settles it is it left `undecided`, as no cubes add up to a cube, which takes Fermat's last theorem to tell: deciding such a way in general is not possible. A branch inside `map` or `fold` is measured as the ways one element takes through the body (`each of $.lines[]: …`): an element of an array the input holds stands at that array's element position, so its borders and classes are drawn there and `generate` composes them, and a way through the body by a row holding one element that takes it. Branch-free collection expressions remain eligible for strict checking. Array-length relationships and arbitrary fold postconditions beyond the declared accumulator contract are not inferred.
266
324
 
267
325
 
268
326
  ## Commands
269
327
 
270
- Chisel requires Node.js 26 or later and uses its built-in Temporal API.
328
+ Chisel runs on Node.js 22.22, 24.15 and 26 or later, and on Bun. Only the temporal schemas (`instant`, `date`, `time`, `datetime`) need the Temporal API: Node.js 26 has it built in, and on earlier runtimes import a polyfill such as `temporal-polyfill/global` before using them. A specification without temporal values needs nothing more. The test suite loads `temporal-polyfill` where the runtime lacks Temporal, and CI runs it on Node.js 22, 24 and 26.
271
329
 
272
330
  ```sh
273
331
  npm install
@@ -285,6 +343,8 @@ node dist/cli.js check ./cancel-order.spec.ts --strict
285
343
 
286
344
  `check` reports the current state without failing by default. `--strict` exits with status 1 while examples are unanswered, input/result/effect variants, classes or border points are uncovered, the implementation is absent or pending, control policies are incomplete, or the implementation disagrees with an example. It also fails for `undetermined`: missing measurements, unproved constructions, exhausted budgets, and opaque callback bodies must not certify a build. `adequate` is now exactly `verdict === "satisfied"`.
287
345
 
346
+ Invalid command lines, including unknown subcommands, unknown flags, and missing required arguments, exit with status 2. Errors while executing a command exit with status 1.
347
+
288
348
  ## Progressive demo
289
349
 
290
350
  The [hotel reservation demo](./examples/progressive-demo/README.md) runs the complete declaration → generation → human answer → refinement → implementation sequence.
@@ -304,11 +364,26 @@ The analyzer follows the example-adequacy model of [Souther](https://github.com/
304
364
 
305
365
  Besides `c.instant()` for an exact moment (`Temporal.Instant`), `c.date()`, `c.time()` and `c.datetime()` hold a calendar date, a time of day and a wall-clock date and time (`Temporal.PlainDate`, `PlainTime` and `PlainDateTime`); a condition orders values of one of these types, and ordering two types against each other does not compile.
306
366
 
367
+ A model moves one of these values by a whole number of one unit with `c.plus(value, amount, unit)` and `c.minus(value, amount, unit)`, and counts the whole units from one to another with `c.between(start, end, unit)`, as Temporal's `add`, `subtract` and `until` do:
368
+
369
+ ```ts
370
+ c.model("plan the receipt", order => ({
371
+ result: {
372
+ outcome: "planned",
373
+ expectedOn: c.plus(order.exFactoryOn, order.leadTimeDays, "days"),
374
+ daysLate: c.between(order.exFactoryOn, order.completedOn, "days"),
375
+ },
376
+ effects: [],
377
+ }))
378
+ ```
379
+
380
+ The unit is the type's: a date takes `years`, `months`, `weeks` and `days`, a time of day and an instant `hours`, `minutes`, `seconds` and `milliseconds`, and a date-time both, so `c.plus(time, 1, "days")` does not compile. The amount is a whole number, which may be negative. A month or year that lands past the target month's last day moves to that day (`2026-01-31` plus a month is `2026-02-28`) unless `{ overflow: "reject" }` asks for the value to be refused instead; a time of day wraps at midnight (`23:00` plus 90 minutes is `00:30`); `between` drops a part of a unit, toward zero, and is negative when the end comes first; it counts a unit of fixed length (`weeks` to `milliseconds`) between dates or date-times of two calendars in the ISO calendar, since such a unit counts alike in every calendar, and leaves months and years to Temporal, which refuses to count them across calendars. `verify` places a date, a date-time and an instant on one line of nanoseconds since 1970-01-01, so a move by a unit of fixed length (`weeks` to `milliseconds`) and a count between two such values are proved from the bounds of their parts, as integer arithmetic is: `c.plus(on, by, "days")` with `on` at most `2099-12-31` and `by` from 0 to 365 meets a `c.date().max(...)` a year later, and is refuted with a counterexample against one that ends on `2099-12-31`; a date with no bounds may be moved out of the range Temporal holds, so it is left undetermined. A month or year has no fixed length and is left undetermined too, and so is a count in `weeks` whose end may lie within a week of that range, since Temporal places the week past the end to round the count. A moved time of day meets a `c.time()` without bounds when its amount is a safe integer short of the 2^53 seconds Temporal refuses as a duration; an amount that may lie past the safe integers leaves any move undetermined.
381
+
307
382
  Any schema takes `.describe("...")`, as in zod, and a behavior a `description`, saying what they mean to the people reading the specification; neither changes what is parsed or measured, and an optional field carries the description of what it holds. `variants("状態", { 下書き: c.object({...}).describe("まだ申請していない"), ... })` names each case.
308
383
 
309
- A `c.number()` has no value next to a bound, so `price < 1000` owes a row at 1000 but cannot name the one just below it. Where the digits after the point are fixed, as for an amount in cents or a weight in grams, `c.decimal(2)` (or `decimal(3)`) says so. Its values are [decimal.js](https://github.com/MikeMcl/decimal.js) `Decimal`s, so arithmetic on them is exact (`new Decimal("0.1").plus("0.2")` is `0.3`): a value with more digits is refused, a bound steps by one unit of the last digit, so the same guard owes a row at 999.99 too, and `generate` writes the rows as `new Decimal("999.99")`, importing decimal.js beside chisel. A bound written off that grid, such as `$gte(new Decimal("0.004"))` in cents, draws the border of `$gte(new Decimal("0.01"))`. An equality with such a value settles without a row (`$ne(new Decimal("0.005"))` in cents always holds, and `$eq` never does), so it is refused wherever it is written: `implement` refuses it in a guard (`guard in 半端な額 compares $.合計 with 0.005, which no decimal(2) holds: $.合計 != 0.005`), `refine` and its shorthands in an invariant (`refine compares $.合計 with 0.005, …`), and `behavior` in an `ensures` clause (`Ensures 半端にしない compares value.合計 with 0.005, …`). A decimal is compared only with a decimal: two of them draw a border on their difference in units of the finer scale.
384
+ Use `c.int()` for whole units such as yen and pieces, and `c.decimal(scale)` for values with fixed fractional digits. A `c.number()` has no value next to a bound, so `price < 1000` owes a row at 1000 but cannot name the one just below it. Where the digits after the point are fixed, as for an amount in cents or a weight in grams, `c.decimal(2)` (or `decimal(3)`) says so. Its values are [decimal.js](https://github.com/MikeMcl/decimal.js) `Decimal`s, so arithmetic on them is exact (`new Decimal("0.1").plus("0.2")` is `0.3`): a value with more digits is refused, a bound steps by one unit of the last digit, so the same guard owes a row at 999.99 too, and `generate` writes the rows as `new Decimal("999.99")`, importing decimal.js beside chisel. A bound written off that grid, such as `$gte(new Decimal("0.004"))` in cents, draws the border of `$gte(new Decimal("0.01"))`. An equality with such a value settles without a row (`$ne(new Decimal("0.005"))` in cents always holds, and `$eq` never does), so it is refused wherever it is written: `implement` refuses it in a guard (`guard in 半端な額 compares $.合計 with 0.005, which no decimal(2) holds: $.合計 != 0.005`), `refine` and its shorthands in an invariant (`refine compares $.合計 with 0.005, …`), and `behavior` in an `ensures` clause (`Ensures 半端にしない compares value.合計 with 0.005, …`). A decimal is compared only with a decimal: two of them draw a border on their difference in units of the finer scale.
310
385
 
311
- The common bounds have zod's shorthands, each desugaring to the same rule `refine` would take: on numbers, decimals and the temporal types `min`, `max`, `gt` and `lt` compare the value (with a bound of the same type, such as `c.date().min(Temporal.PlainDate.from("2026-01-01"))`), and on strings, arrays and records `min`, `max` and `length` compare the length, so the borders keep a value and a length apart. `refine(v => ...)` states anything else, such as a relation between two fields (`.refine(v => v.start.$lte(v.end))`), and takes a name first, as every named construct does (`.refine("starts before it ends", v => v.start.$lte(v.end))`, as do the shorthands, `c.int().min("at least one", 1)`), which the issue for a value breaking it carries as `invariant` (`Invariant starts before it ends violated: $.start <= $.end`) and the borders it draws are labelled with; a value is refused with one issue for every invariant it breaks, and one schema may not name two invariants alike; its callback returns a rule built with term operators, not a boolean, so a condition the analysis cannot read does not type-check. A numeric or decimal term also adds and subtracts, `v.甲.$gte(v.乙.$minus(v.丙))` or `v.甲.$plus(2).$lte(v.乙)`, as Souther conditions do: the comparison reads the value of the expression, and an expression holding a field left out is absent, so the comparison holds. A guard or an input invariant comparing an expression of integer or number fields draws its border on the expression, as Souther does: `甲 >= 乙 − 丙` has its `ON` point at `甲 − 乙 + 丙 = 0` and its `OFF` point at `-1`, and `generate` writes a point by moving a field the expression counts once, trying each in turn until the input takes the row (a point of `2 * 甲 >= 2 * 乙`, which counts none once, is named among those it could not compose), and the guards on one expression are read together, so a point of `甲 >= 乙 − 丙` behind `甲 <= 乙 − 丙` that no value reaches is owed no row, and so is one the fields' own bounds leave the expression no value at (with `甲` and `丙` at least 0 and `乙` at most 0, `甲 − 乙 + 丙` is never below 0, so `OFF` and `OUT` are owed none); a row `generate` moves across an invariant ordering two numbers, such as `correctQty < recordedQty` when `correctQty` is moved to 1, has the other number moved to the nearest value that keeps it (`recordedQty = 2`); an expression over decimals is still listed among the comparisons Chisel cannot read.
386
+ The common bounds have zod's shorthands, each desugaring to the same rule `refine` would take: on numbers, decimals and the temporal types `min`, `max`, `gt` and `lt` compare the value (with a bound of the same type, such as `c.date().min(Temporal.PlainDate.from("2026-01-01"))`), and on strings, arrays and records `min`, `max` and `length` compare the length, so the borders keep a value and a length apart. `refine(v => ...)` states anything else, such as a relation between two fields (`.refine(v => v.start.$lte(v.end))`), and takes a name first, as every named construct does (`.refine("starts before it ends", v => v.start.$lte(v.end))`, as do the shorthands, `c.int().min("at least one", 1)`), which the issue for a value breaking it carries as `invariant` (`Invariant starts before it ends violated: $.start <= $.end`) and the borders it draws are labelled with; a value is refused with one issue for every invariant it breaks, and one schema may not name two invariants alike; its callback returns a rule built with term operators, not a boolean, so a condition the analysis cannot read does not type-check. A numeric or decimal term also adds and subtracts, `v.甲.$gte(v.乙.$minus(v.丙))` or `v.甲.$plus(2).$lte(v.乙)`, as Souther conditions do: the comparison reads the value of the expression, and one holding a field that may be left out is refused, as every comparison reading such a field is (see [absence is a case of a sum](#absence-is-a-case-of-a-sum)). A guard or an input invariant comparing an expression of integer or number fields draws its border on the expression, as Souther does: `甲 >= 乙 − 丙` has its `ON` point at `甲 − 乙 + 丙 = 0` and its `OFF` point at `-1`, and `generate` writes a point by moving a field the expression counts once, trying each in turn until the input takes the row (a point of `2 * 甲 >= 2 * 乙`, which counts none once, is named among those it could not compose), and the guards on one expression are read together, so a point of `甲 >= 乙 − 丙` behind `甲 <= 乙 − 丙` that no value reaches is owed no row, and so is one the fields' own bounds leave the expression no value at (with `甲` and `丙` at least 0 and `乙` at most 0, `甲 − 乙 + 丙` is never below 0, so `OFF` and `OUT` are owed none); a row `generate` moves across an invariant ordering two numbers, such as `correctQty < recordedQty` when `correctQty` is moved to 1, has the other number moved to the nearest value that keeps it (`recordedQty = 2`); an expression over decimals is still listed among the comparisons Chisel cannot read.
312
387
 
313
388
  ```ts
314
389
  const Line = c.object({
@@ -321,7 +396,7 @@ const SubtotalByProduct = c.record(c.int().min(0)).min(1);
321
396
 
322
397
  A record's length is its number of keys, so `SubtotalByProduct` needs at least one product; `generate` writes it as `{ "<key>": 0 }`, one entry showing the shape of its value, the way an array placeholder holds one element.
323
398
 
324
- - **Arms and rules** of an action's `guards`, and the borders and classes its guards draw. A guard compares with the same vocabulary as an invariant: a condition is written on terms, which read a field by its own name, as `run` reads the value (`line.quantity`), and whose operators carry a `$` prefix, so no field name can shadow one: they compare with `$lt`, `$lte`, `$gt`, `$gte`, `$eq` and `$ne`, measure with `$length()`, quantify over array elements with `$all` and `$any`, and combine with `$and`, `$or` and `$not`. A condition becomes a guard with `$else`, which answers when the condition does not hold; that answer is an ordinary result case, so a business rejection is data, not an exception:
399
+ - **Arms and rules** of an action's `guards`, and the borders and classes its guards draw. A guard compares with the same vocabulary as an invariant: a condition is written on terms, which read a field by its own name, as `run` reads the value (`line.quantity`), and whose operators carry a `$` prefix, so no field name can shadow one: they compare with `$lt`, `$lte`, `$gt`, `$gte`, `$eq` and `$ne`, measure with `$length()`, read a string as `String.prototype.trim`, `toLowerCase` and `toUpperCase` give it back with `$trim()`, `$lowercase()` and `$uppercase()` (in the order written, the value itself left as it is, so `reason.$trim().$length().$gt(0)` refuses a reason of only spaces and `code.$trim().$lowercase().$eq("abc")` matches ` ABC `; a bound no string reads as, such as `"ABC"` after `$lowercase()`, has no point at it, so such an equality never holds and owes no row), quantify over array elements with `$all` and `$any`, and combine with `$and`, `$or` and `$not`. A condition becomes a guard with `$else`, which answers when the condition does not hold; that answer is an ordinary result case, so a business rejection is data, not an exception:
325
400
 
326
401
  ```ts
327
402
  const implementation = c.implement(checkout, {
@@ -339,7 +414,9 @@ const implementation = c.implement(checkout, {
339
414
  });
340
415
  ```
341
416
 
342
- Every guard has a `holds` and an `else` arm, and every case of a `match` is an arm (a `match` that leaves out a case of the `variants` or value of the `enum` it matches on, or names one it does not have, fails to compile, and one on a sum that may be left out, or is held by something that may be, is refused by `implement`, since no case would take its absence: write the absence as a case of the sum); each way through the guards is a rule. Where every value the guards and the `match` read is a boolean, an `enum` or a `variants` case and their combinations are few enough (`feasibility.combinations`), Chisel tries each combination the invariants on those values keep and lists only the ways some combination takes, since the ways `$and`/`$or` spell grow exponentially with the conditions while the combinations stay few; otherwise it lists at most `feasibility.ways` ways (10000 by default, `chisel check --feasibility-ways <n>`) and leaves a decision with more unmeasured instead. A way or an arm no row took is a gap only when some row could take it: where the conditions it passes contradict each other or the invariants of the values they read (`$.x >= 10` holds and `$.x >= 5` fails), no row is owed, and that includes an invariant relating several booleans, enums or `variants` cases by `==`/`!=` (with each other or with a value) and `$and`/`$or`/`$not`, whose combinations Chisel tries up to a limit (`c.check(specification, { feasibility: { combinations } })`, `chisel check --feasibility-combinations <n>`, 4096 by default; past it the way is undecided); where a condition Chisel cannot read (`all`/`any`) shares a value with another, it is undecided, which leaves the verdict `undetermined` rather than `not_satisfied`. Both are counted under their reason instead of listed. A guard border point is settled the same way, from the conditions a row has passed before it reaches the comparison. That holds for a comparison of two positions too, read on their difference: behind a guard `x <= y`, the `IN (> 0)` point of a later `x >= y` is one no row can reach, so no row is owed there, as Souther refutes a point the rules leave no value at. `generate` offers a row for each way no row takes but some row could: where the way ends in a `match`, it moves the matched field of a row that reaches it, and, with `chisel generate --ways` (`c.generate(examples, implementation, { ways: true })`), where every condition on the way compares a boolean, an `enum` or a `variants` case with a value (`==`/`!=`), it writes all of them at once, so a way that needs several values chosen together (`$.甲 == "x"` and `$.乙 == "y"`) gets a row too. Without it such a way is only named, since every way through `$and`/`$or` is its own row and their number grows quickly with the conditions. Wherever a row `generate` writes would break an invariant relating several booleans, enums or `variants` cases, the other values those invariants reach are chosen again so the row keeps them, and a way row is tried from every answered row of the case before its placeholder. A way with an ordering, a length, `all`/`any` or a field inside a `variants` field it cannot compose is named in its output instead. A guard comparing a position with a constant divides it into classes and owes all four border points; one comparing two positions with an order draws its border on their difference, while an equality between two positions draws none, since its `holds` and `else` arms already ask for a row on each side of the line. A guard point is met only by a row that reached the comparison.
417
+ Every guard has a `holds` and an `else` arm, and every case of a `match` is an arm (a `match` that leaves out a case of the `variants` or value of the `enum` it matches on, or names one it does not have, fails to compile, and one on a sum that may be left out, or is held by something that may be, is refused by `implement`, since no case would take its absence: write the absence as a case of the sum); each way through the guards is a rule. Where every value the guards and the `match` read is a boolean, an `enum` or a `variants` case and their combinations are few enough (`feasibility.combinations`), Chisel tries each combination the invariants on those values keep and lists only the ways some combination takes, since the ways `$and`/`$or` spell grow exponentially with the conditions while the combinations stay few; otherwise it lists at most `feasibility.ways` ways (10000 by default, `chisel check --feasibility-ways <n>`) and leaves a decision with more unmeasured instead. Before it counts, it prunes and splits: a way whose steps hold one value equal to two constants (`$.type == "a"` then `$.type == "b"`), or a `match` against a comparison it contradicts, is never listed; and the fields of a model's answer that read nothing another field computes (each reached through plain objects and lists, and the bodies of binds of a value that chooses nothing) are independent parts, whose ways are listed and counted apart (`result.sets.tierChanged: …`) and add up rather than multiply, a run handing each part's steps apart as it does an iteration's. A model answering nine independent verdicts of a dozen choices each has a few hundred ways, not millions. `verify` proves such a model part by part: the answer's frame with each part standing as any value of the schema at its place, each part against that schema, and each `ensures` clause over the ways of the parts it reads only (where the frame is not proved so, as when an invariant relates two parts, it proves every way together as before). A way's `==`/`!=` between two booleans, enums or sum tags is settled with them by trying their values, and between two strings no invariant narrows by which of them the way makes equal; a field of a sum's case is read with the schema the case gives it, since a way reads one only where it settled the case. A quantified condition and the same condition written negated (`any(xs, x => all(ys, y => y != x))` and `all(xs, x => any(ys, y => y == x))`) are known to be each other's negation. Such a decision is reported in `toBeChangedFirst` with what to change, read off the model's shape without listing its ways (`c.modelChanges(specification, options)`, which `chisel check` prints under `計測の前に:` before it measures in text mode; with `--json` the guidance is in the report's `toBeChangedFirst`): the ways of a model multiply across the parts a way goes through all of, so the report names parts, chosen greedily and each itself within the limit, that, declared as behaviors of their own and called as dependencies (whose answer is read as a value, their choices measured once in their own reports), leave the rest within the limit (a guide, not the smallest split there is); for guards, it names the stages that, joined with `compose`, are each within it (or says no such split exists). Nothing it says depends on the measurement, so the model can be changed as soon as it is printed. A check that runs long says on stderr which behavior and phase it is on, after three seconds and then once a minute (`progress` in `CheckOptions` and `GenerationOptions`).
418
+
419
+ Following Souther 0.5.0, a check also reports `walks`: every `fold` a model writes is run, for each answered row that took a second element, with the walk stopping after its first step and with every step handed the seed; a rewrite no row tells apart is `not told`, which makes the specification inadequate, and `generate` offers a row with the walked list grown to two elements. It reports `stops`: every operation, temporal move and construction a model writes is judged once as `may stop` (with an input that stops there, and for a division by an input field the invariant that keeps it from stopping), `never stops` (shown by an exhaustive run, a proved construction or the exact range of the operation) or `not resolved`, which leaves the verdict `undetermined`. Guard borders over one computation owe their weights from the lines beside them once, however many thresholds it is compared with. `generate` also offers suggested rows that owe nothing: the inputs a called behavior's recorded rows were written with, asked in its caller. A condition may also relate a place to a value: `v.email.$endsWith("@example.com")`, `$startsWith`, `$contains`, `v.rates.$hasKey("USD")` on a record and `v.tags.$includes("vip")` on an array; against a written value it divides the place into the classes the relations come out in, each owed a row, and a way whose relations contradict each other by their laws owes none. `c.decimal()` without a scale takes any finite decimal, `c.round(value, scale, mode)` and `c.divide(a, b, scale, mode)` round exactly at any scale, and a run with no room to write an answer fails as `OutOfRoom`, which `check` reports apart from the model's failures. A fold or map takes its step as a value too: `c.fold(element, output, xs, seed, c.choose(cond, c.step<[number, number], number>((total, x) => …), c.step<[number, number], number>(…)))` chooses the step once, before the walk. A way or an arm no row took is a gap only when some row could take it: where the conditions it passes contradict each other or the invariants of the values they read (`$.x >= 10` holds and `$.x >= 5` fails), no row is owed, and that includes an invariant relating several booleans, enums or `variants` cases by `==`/`!=` (with each other or with a value) and `$and`/`$or`/`$not`, whose combinations Chisel tries up to a limit (`c.check(specification, { feasibility: { combinations } })`, `chisel check --feasibility-combinations <n>`, 4096 by default; past it the way is undecided); where a condition Chisel cannot read (`all`/`any`) shares a value with another, it is undecided, which leaves the verdict `undetermined` rather than `not_satisfied`. Both are counted under their reason instead of listed. A guard border point is settled the same way, from the conditions a row has passed before it reaches the comparison. That holds for a comparison of two positions too, read on their difference: behind a guard `x <= y`, the `IN (> 0)` point of a later `x >= y` is one no row can reach, so no row is owed there, as Souther refutes a point the rules leave no value at. `generate` offers a row for each way no row takes but some row could: where the way ends in a `match`, it moves the matched field of a row that reaches it, and, with `chisel generate --ways` (`c.generate(examples, implementation, { ways: true })`), where every condition on the way compares a boolean, an `enum` or a `variants` case with a value (`==`/`!=`), it writes all of them at once, so a way that needs several values chosen together (`$.甲 == "x"` and `$.乙 == "y"`) gets a row too. Without it such a way is only named, since every way through `$and`/`$or` is its own row and their number grows quickly with the conditions. Wherever a row `generate` writes would break an invariant relating several booleans, enums or `variants` cases, the other values those invariants reach are chosen again so the row keeps them, and a way row is tried from every answered row of the case before its placeholder. A way with an ordering, a length, `all`/`any` or a field inside a `variants` field it cannot compose is named in its output instead. A guard comparing a position with a constant divides it into classes and owes all four border points; one comparing two positions with an order draws its border on their difference, while an equality between two positions draws none, since its `holds` and `else` arms already ask for a row on each side of the line. A guard point is met only by a row that reached the comparison.
343
420
 
344
421
  Any free-form `run` closure, including `action({ run })` and match handlers, may contain hidden branches and constructions. Declared guards still have coverage measurements, but `measures.constructions` is `undetermined`, so the specification cannot be certified. The same holds for a comparison inside `rules` that Chisel cannot draw a line from.
345
422
 
@@ -350,7 +427,7 @@ A behavior can state what it ensures of its answer, and declare the outside worl
350
427
  ```ts
351
428
  const findMember = c.behavior("find-member", {
352
429
  input, result, effects,
353
- requires: { now: c.dependency(c.instant()), lookup: c.dependency(c.string(), c.boolean()) },
430
+ dependencies: { now: c.dependency(c.instant()), lookup: c.dependency(c.string(), c.boolean()) },
354
431
  ensures: clause => [
355
432
  clause.when("a found member is the one asked for", ["found"], (asked, answer) =>
356
433
  asked.id.$gt(0).$and(answer.id.$eq(asked.id)),
@@ -359,10 +436,59 @@ const findMember = c.behavior("find-member", {
359
436
  });
360
437
  ```
361
438
 
362
- Every answer an example writes, the model produces or a conformance subject returns is held to the clauses, and a comparison of the input with a constant draws a border. Clause names must be distinct, and `check` says of every part of every rule how much of it the checker can read (`derivable`, `exact match`, `always holds`, `never holds` or `runtime only`) and which answer cases no clause states anything about. Example rows stand in for value dependencies with `with: { now: ... }` (`generate` writes one on every row it offers, the placeholder of the dependency's type under what the row it moved from writes, so a generated row runs as it is pasted), and a specification stands in for function dependencies with `fakes: [fake(findMember, "lookup", [["m-1", true]], { otherwise: false })]`. An action reads a value dependency in a guard condition through the second argument of its `guards` builder, `action("future only", { guards: (request, deps) => [deps.now.$lt(request.at).$else(...)], run: ... })`: the condition is evaluated against the stand-in a row writes with `with`, and the comparison is measured like any other (here, a border on `deps.now − @case.at`). Function dependencies stay out of conditions. A function dependency can be another behavior, `requires: { stock: dependency(checkStockExamples) }`: a fake table for it is then held to that behavior's `ensures` (a row that breaks one is an error) and to its recorded rows (a row answering differently from one is a warning).
439
+ Every answer an example writes, the model produces or a conformance subject returns is held to the clauses, and a comparison of the input with a constant draws a border. Clause names must be distinct, and `check` says of every part of every rule how much of it the checker can read (`derivable`, `exact match`, `always holds`, `never holds` or `runtime only`) and which answer cases no clause states anything about. Example rows stand in for value dependencies with `with: { now: ... }` (`generate` writes one on every row it offers, the placeholder of the dependency's type under what the row it moved from writes, so a generated row runs as it is pasted), and a specification stands in for function dependencies with `fakes: [fake(findMember, "lookup", [["m-1", true]], { otherwise: false })]`. An action reads a value dependency in a guard condition through the second argument of its `guards` builder, `action("future only", { guards: (request, deps) => [deps.now.$lt(request.at).$else(...)], run: ... })`: the condition is evaluated against the stand-in a row writes with `with`, and the comparison is measured like any other (here, a border on `deps.now − @case.at`). Function dependencies stay out of conditions. A function dependency can be another behavior, `dependencies: { stock: dependency(checkStockExamples) }`: a fake table for it is then held to that behavior's `ensures` (a row that breaks one is an error) and to its recorded rows (a row answering differently from one is a warning).
363
440
 
364
441
  `check` now enforces feasible pairs of classes as obligations (`measures.pairs`), and retains the older reached counts in `pairs` for display, over the same classes the report lists (including those guard thresholds draw, and leaving excluded classes out), and `check --json` writes the whole report as one document, described by the closed JSON Schema in [`schema/report.schema.json`](schema/report.schema.json) (published as `@toiroakr/chisel/report.schema.json`). The arms, rules, and comparisons measures retain their availability and weakening metadata; pairs record each obligation and constructions record each proof; every border point, arm, way, and pair carries a stable `obligationId`; `incompleteness` lists the rows that were not observed (not run for want of a stand-in, or not come back); and `sources` names the spec file each report's `source` refers to. `schemaVersion` is raised only when a field is removed or renamed.
365
442
 
443
+ ### Reading a union, and clauses about some of its cases
444
+
445
+ The terms an `ensures` clause is handed expose the fields of every case of a sum, typed by the cases that declare them, so `read.expiresAt` needs no cast where only the `recorded` case has it. A term of a sum is a path, and a path no case of the input holds reads as absent, which makes a comparison hold: `c.lte(read.expiresAt, read.now)` is true for an input of another case. Name the case first, as the absence check expects: `c.and(c.eq(read.state, "recorded"), c.lte(read.expiresAt, read.now))`. To say a clause of some input cases and no others, write it with `c.given(name, cases, rule)`, which `ensures` takes beside the clauses it builds; its `read` is then typed as those cases, and the rule is held of inputs in them only:
446
+
447
+ ```ts
448
+ ensures: () => [
449
+ c.given("a passed expiry is a candidate", ["recorded"], (read, answer) =>
450
+ c.or(c.eq(answer.verdict, "candidate"), c.not(c.lte(read.expiresAt, read.now)))),
451
+ ],
452
+ ```
453
+
454
+ `clause.when(name, resultCases, rule)` narrows by the answer's case. `c.protocol` and `c.given` are functions of their own rather than methods of the builders, so a bundle holds their checks only where a behavior writes one.
455
+
456
+ ## The calls a behavior makes
457
+
458
+ `effects` declares which calls a behavior makes; `ensures` says nothing of them. `protocol` says what order they come in and when they may be made, and `verify` and `checkProtocol` hold code to it. A workspace is deleted only after its expiry is read again, and only if that second read still says it has passed: someone may have renewed it in between. The input carries both reads, so the interruption is a pair of values the checks try:
459
+
460
+ ```ts
461
+ const prune = c.behavior("prune one workspace", {
462
+ input: c.variants("state", {
463
+ listed: c.object({ expiresAt: c.jsDate(), recheckedExpiry: c.jsDate(), now: c.jsDate() }),
464
+ unlisted: c.object({}),
465
+ }),
466
+ result: c.variants("verdict", { deleted: c.object({}), kept: c.object({}) }),
467
+ effects: c.variants("type", { recheckExpiry: c.object({}), deleteWorkspace: c.object({}) }),
468
+ protocol: c.protocol(rule => [
469
+ rule.before("recheckExpiry", "deleteWorkspace"), // every deleteWorkspace comes after a recheckExpiry
470
+ rule.only("deleteWorkspace", read => c.and(c.eq(read.state, "listed"), c.lte(read.recheckedExpiry, read.now))),
471
+ rule.atMostOnce("deleteWorkspace"),
472
+ ]),
473
+ });
474
+ ```
475
+
476
+ Names in the rules are the declared effects (a name that is not one is refused where it is written), and an `only` rule reads the input.
477
+
478
+ - **A model** (`c.implement` with `c.model`): `performSync` and `perform` refuse effects that break a rule (`Protocol recheckExpiry before every deleteWorkspace does not hold of the effects deleteWorkspace`), an example row whose expected effects break one fails in `check`, and `verify` proves each way through the model, reading the list of effects the way answers: `before` and `atMostOnce` by the list, `only` from the way's conditions. A way where the proof fails is `refuted` with an input when a run on the domain it samples breaks the rule (a model that decides on the first read, `expiresAt <= now`, is refuted by an input where `recheckedExpiry` is after `now`), and `undetermined` otherwise. A behavior with a protocol is `verified` only when every way is proved, so an effects list the proof cannot read as a list of declared calls leaves it undetermined.
479
+ - **Code that makes its own calls** (a function that lists, asks, then deletes) is run by `checkProtocol` from `@toiroakr/chisel/full`. It hands the code an `api` with one function per declared effect, records each call, and answers the calls from the input:
480
+
481
+ ```ts
482
+ const report = await checkProtocol(prune, async (api, input) => {
483
+ if (input.state !== "listed") return;
484
+ const again = await api.recheckExpiry();
485
+ if (again <= input.now) await api.deleteWorkspace();
486
+ }, { answers: { recheckExpiry: input => input.recheckedExpiry } });
487
+ // { status: "passed", checked: 126, exhaustive: false, failures: [] }
488
+ ```
489
+
490
+ A call the behavior does not declare (`api.dropDatabase()`) fails the input even where the code catches what it throws. A failure names the input, the calls made and the rule: `{ input: { state: "listed", expiresAt: …, recheckedExpiry: <after now>, now: … }, calls: ["recheckExpiry", "deleteWorkspace"], reason: "Protocol deleteWorkspace only when … does not hold" }`. `inputs` runs the inputs you write instead of the ones the schema gives (a date comes with the points a millisecond and a day either side, so before, equal and after are all tried), and `exhaustive` says whether the inputs run were every input the schema allows: a pass over a sample says nothing of the rest.
491
+
366
492
  ## One model, several behaviors
367
493
 
368
494
  Behaviors that work on one record can share its model as their input: `input: Report` in each of them, so a state added to `Report` reaches every behavior at once. Each of them is then asked about every field of every state, including fields its answer never turns on. `disregards` says which, per input case like `cases`, with `$default` for every case not written; `r => [r]` disregards a whole case:
@@ -387,6 +513,198 @@ c.implement(approve, {
387
513
 
388
514
  A disregarded field draws no classes of its type, no invariant borders and no borders an `ensures` clause draws on it, so `generate` offers no row that only moves it; where a guard or a `match` reads it, it keeps the classes the guard draws or its own classes, since the arms turn on them. Every input case is still owed its row, guards still draw their borders and arms from the whole input, and an invariant that leaves a disregarded field empty is still a model error. Rows keep the whole record, so `c.test` hands production code what it takes. `check` holds the claim: it moves the disregarded fields of an answered row, each element of an array and each entry of a record on its own, through every combination of their other classes and of the invariant border points they would have owed (`IN (> 0)` for an `int().min(0)` at 0), smallest first, runs the model on each and fails the row on the first answer that changes, naming the fields it moved (`approve disregards @submitted.urgent, but its answer changed when @submitted.urgent was true`). A row with more than 255 combinations the input can hold, or more than 4096 candidates before those it cannot hold are left out, is not tried (the limits are the caller's: `c.check(specification, { disregards: { combinations, candidates } })`, or `chisel check --disregard-combinations <n> --disregard-candidates <n>`); it is listed in `incompleteness` as `disregards not checked` and leaves the verdict `undetermined`. `cases.$default` decides every case `cases` leaves out; it is one decision, so its arms and ways are listed once and owed wherever one of its cases can reach them, a `c.todo` there leaves each of its cases pending, and a `$default` beside cases that decide every case is refused. An input case cannot be named `$default`. [`examples/expense-report/`](examples/expense-report/) writes three behaviors over one five-state model both ways.
389
515
 
516
+ ## One reducer for runtime and exhaustive checking
517
+
518
+ For a finite command domain, `machine` uses one expression for both runtime state updates and exhaustive reachability checking. Commands emitted by a transition run through that same reducer in order. The returned state is yours to persist wherever you choose. Import the execution API from `@toiroakr/chisel/runtime`; put verification properties in a separate module importing `@toiroakr/chisel/verification`. This keeps invariant definitions, model checking, TLA+ translation, and `tla-ts` out of the production import graph. `/runtime` is the method-based runtime (it also exports the behavior runtime described above, with the methods); the previous combined API is available from `/full`.
519
+
520
+ ```ts
521
+ import * as c from "@toiroakr/chisel/runtime";
522
+
523
+ const State = c.int().min(0).max(2);
524
+ const Command = c.enum(["go", "finish"] as const);
525
+ export const workflow = c.machine("two steps", {
526
+ state: State,
527
+ command: Command,
528
+ initial: [0],
529
+ update: (state, command) => ({
530
+ state: c.choose(state.$lt(2), state.$plus(1), state),
531
+ commands: c.choose(command.$eq("go"), ["finish" as const], [] as const),
532
+ }),
533
+ });
534
+
535
+ c.runMachine(workflow, 0, "go"); // { state: 2, steps: [go: 0→1, finish: 1→2] }
536
+ ```
537
+
538
+ In a separate `workflow.spec.ts` file used by CI:
539
+
540
+ ```ts
541
+ import { invariant, specifyMachine, checkMachine } from "@toiroakr/chisel/verification";
542
+ import { workflow } from "./workflow.js";
543
+
544
+ export const specification = specifyMachine(workflow, {
545
+ invariants: [invariant<number>("at most two", state => state.$lte(2))],
546
+ });
547
+ checkMachine(specification); // { status: "held", states: 3, transitions: 6 }
548
+ ```
549
+
550
+ [`examples/order-machine.ts`](examples/order-machine.ts) shows a typed order workflow with `submit`, internal `allocate`, and `receive` commands. [`examples/order-machine.spec.ts`](examples/order-machine.spec.ts) declares its invariant and transition property. `runMachine` returns each intermediate step, while `checkMachine` checks every command from every reachable state. A receipt before issuance or beyond the ordered quantity intentionally leaves the state unchanged; the invariant checks state safety rather than command acceptance.
551
+
552
+ `requires` in `specifyMachine` states, per command, the states and commands in which the command is meant to change the state (`requires: { allocate: order => order.phase.$eq("approved") }`). `checkMachine` is `broken` when a step changes the state although its precondition is false, or leaves the state unchanged although it holds, and the counterexample is the shortest command sequence that reaches such a step. A command without an entry is not held to one.
553
+
554
+ `columns` in `specifyMachine` (`columns: ["phase"]`) names the state fields that tell the rows of a table apart. Then `checkMachine` adds `matrix` to its report: for each value of the columns reached and each command, whether the command `changes` the state (`always`, `sometimes` or `never`, over every reachable state that shares those column values) and, where `requires` has an entry, whether its `precondition` holds. `model-check` prints it, and `--json` carries it. For the order workflow, `receive` with one unit in `phase=issued` reads `changes sometimes, precondition sometimes`, since it takes effect only while the ordered quantity has room. A cell no run reached, such as one cut off by `maxCommands`, reads `unknown` rather than `never`. The table lists each command as it is invoked from a state, so a state that exists only between a command and the commands it emits (`approved` in the order workflow) has no row; the precondition of an emitted command is still checked at every step. A `sometimes` that you expected to be `always` or `never` is a row to read. Columns are always chosen by you: a state field with many values (a counter, an id) would give one row per value.
555
+
556
+ A command that writes to something outside the machine returns `effects` instead of `state`. Each `c.effect(name, stateAfter)` names a write and the state the machine is in once it has succeeded; the state after the command is the one after the last effect, and with no effects the state is unchanged. The expression stays pure: the effect only says what the state would be.
557
+
558
+ ```ts
559
+ update: (state, command) => ({
560
+ effects: [
561
+ c.effect("writeLabel", { ...state, label: "in-progress" }),
562
+ c.effect("runScript", { ...state, migrated: true }),
563
+ c.effect("writeLabel", { ...state, label: "checkpoint" }),
564
+ ],
565
+ }),
566
+ ```
567
+
568
+ `checkMachine` explores both outcomes of every effect. A failed effect stops the command, drops the commands it would have emitted and leaves the state as it was before that effect, so the writes before it stay. Where a failure should leave something else, write it: `c.effect("runScript", after, { failure: state })` rolls the whole command back. Invariants, transition properties and preconditions are held on every outcome, the states a failure leaves are reachable states from which every command is explored (so an invariant such as "a half-finished deploy always has a label `resolve` accepts" is held there too), and a counterexample names the effect that failed (`... failed after runScript failed`). These properties are held on the state each outcome ends in, not on the state between two effects of one command that went on to fail (see `crashes` below), and the checker does not say whether a sequence of commands eventually converges. A command that stopped at a failed effect may have written nothing yet, so a precondition that held is not held against it for leaving the state unchanged. `runMachine(machine, state, command, { fails: effect => effect.name === "runScript" })` follows the machine with the effects you say failed, and each step lists what `performed`; `chisel run-machine ... --fail runScript` does the same. `maxOutcomes` bounds the outcomes explored for one command (default 1000). The TLA+ translation makes each effect a choice between its success and its failure, and `--engine tla` and `prove-machine` read effects the same way.
569
+
570
+ A process can also die between two effects, and then no failure handling runs. `specifyMachine(machine, { crashes: true })` makes `checkMachine` explore a death before the first effect of each command and after each effect. The state the death leaves is a reachable state from which every command is explored, a death skips the failure handling (a `failure` state names what a failed effect leaves, not what a death leaves, so the writes of the effects already done stay), a death after the last effect loses the commands the command would have emitted, and the commands still queued behind it die with the process, so the state a death leaves is where the next command starts. Take a checkout that reserves stock and then charges the customer, each effect rolling the whole command back when it fails:
571
+
572
+ ```ts
573
+ import * as c from "@toiroakr/chisel/runtime";
574
+ import { invariant, specifyMachine, checkMachine } from "@toiroakr/chisel/verification";
575
+
576
+ const checkout = c.machine("checkout", {
577
+ state: c.object({ reserved: c.boolean(), charged: c.boolean() }),
578
+ command: c.enum(["checkout"]), initial: [{ reserved: false, charged: false }],
579
+ update: state => ({
580
+ effects: [
581
+ c.effect("reserve", { reserved: true, charged: state.charged }, { failure: state }),
582
+ c.effect("charge", { reserved: true, charged: true }, { failure: state }),
583
+ ],
584
+ }),
585
+ });
586
+ const leak = invariant("a reservation is never left unpaid", state => state.reserved.$eq(false).$or(state.charged.$eq(true)));
587
+ checkMachine(specifyMachine(checkout, { invariants: [leak] })); // held
588
+ checkMachine(specifyMachine(checkout, { invariants: [leak], crashes: true })); // broken: checkout died after effect 1 (reserve)
589
+ ```
590
+
591
+ A command without effects has no point to die at, and a command that stopped by dying is held to its precondition as a command that stopped at a failed effect is. `runMachine` takes `dies: point => point.completed === 1` to follow such a run, and `chisel run-machine ... --die-after 1` does the same. In TLA+ a death is one more outcome of the command, so `--engine tla` and `prove-machine` read it too.
592
+
593
+ ### Running a machine in production
594
+
595
+ `runMachine` only follows the machine; `driveMachine` runs it. The transition that `checkMachine`, `model-check` and `prove-machine` read decides each next effect, and the `perform` you pass makes the outside world reach the state the effect names, so production code holds no second copy of the order of the steps or of what a failure leaves:
596
+
597
+ ```ts
598
+ const { state, failures } = await c.driveMachine(order, current, { type: "submit" }, {
599
+ perform: async effect => { await reconcile(effect.before, effect.after); },
600
+ });
601
+ ```
602
+
603
+ `perform` gets the effect's name, its index and command, the state before it and the state it is to leave. When it returns, the effect succeeded; when it throws or rejects, the effect failed, and the command ends in the effect's failure state and drops the commands it would have emitted, exactly the outcome `checkMachine` explored. The error is listed in `failures` instead of thrown. `perform` may return `{ commands }`: what it observed, run as commands after those the transition emitted. Every command of the domain is explored in every reachable state, so these are checked like any other. A transition still cannot call a dependency; what reaches outside the machine is an effect.
604
+
605
+ Two runs of one flow can also work on the same state at once. `checkInterleavings(specification, { copies: [commandA, commandB] })` runs one copy per command against a single shared state. A copy reads the state when it starts a command, then performs that command's effects one step at a time, and every order in which the steps of the copies interleave is explored. An effect writes only the fields it changes from what its copy last saw (or the fields `writes: ["stock", "a"]` names, which must be fields of the state) onto the state as it is by then, so a write computed from a stale read overwrites what another copy wrote since, and `c.effect(name, after, { ifUnchanged: true })` applies only if nothing was written since the copy read the state, otherwise the copy ends `refused` with the shared state unchanged. Take two customers buying the last unit of a stock, each copy reading the stock and then writing it with its own flag:
606
+
607
+ ```ts
608
+ const shop = c.machine("shop", {
609
+ state: c.object({ stock: c.int().min(0).max(1), a: c.boolean(), b: c.boolean() }),
610
+ command: c.variants("type", { buy: c.object({ customer: c.enum(["a", "b"]) }) }),
611
+ initial: [{ stock: 1, a: false, b: false }],
612
+ update: (state, command) => ({
613
+ effects: c.choose(state.stock.$gte(1), [
614
+ c.effect("take", {
615
+ stock: state.stock.$minus(1),
616
+ a: c.choose(command.customer.$eq("a"), true, state.a),
617
+ b: c.choose(command.customer.$eq("b"), true, state.b),
618
+ }, { ifUnchanged: true }), // drop the option to see the lost update
619
+ ], []),
620
+ }),
621
+ });
622
+ const once = invariant("the last unit is sold once", state => state.a.$eq(false).$or(state.b.$eq(false)));
623
+ const specification = specifyMachine(shop, { invariants: [once] });
624
+ checkInterleavings(specification, { copies: [{ type: "buy", customer: "a" }, { type: "buy", customer: "b" }] });
625
+ // held; terminals: finished/refused, refused/finished, and the sequential finished/finished
626
+ ```
627
+
628
+ Without `ifUnchanged` both copies read a stock of 1 and both write, the report is `broken`, and the counterexample lists the order of the steps (`read`, `read`, `write`, `write`, each with its `copy`). The report's `terminals` list how each copy ended and the state left, so a claim such as "one copy always ends refused when they overlap" can be read off it. A command that declares a state instead of effects reads and writes in one step. `maxCopies` (default 2) and `maxStates` keep the search bounded and leave the result `undetermined` when exceeded, and failures and process deaths are not combined with interleavings. `checkInterleavingsTla` (and `chisel model-check --engine tla`) checks the same invariants and transition properties with each copy as a process of the TLA+ model; it needs a state that is an object, reports `undetermined` for a command that emits commands, and does not list the terminals. Declaring `interleavings: { copies: [...], starts?, maxCopies? }` in `specifyMachine` makes `chisel model-check` check them too, as `<name> (interleavings)`; the copies and starts are checked against the schemas where they are declared.
629
+
630
+ When the code you ship is an existing implementation, not a machine, the machine you check and the code can drift apart. `replayMachine(machine, subject)` (a specification works too) runs the model's transitions against the code. After the shortest command sequence to every state the machine reaches it replays each command, one command at a time from a `reset`, so the transitions that only come back to a state already seen are run as well, and after every command it reads the code's state back and compares it with the machine's using `deepEqual`. The subject is three functions, with the external parts of the code faked by the caller:
631
+
632
+ ```ts
633
+ let store, service;
634
+ const subject = {
635
+ reset: state => { store = fakeStore(state); service = new OrderService(store); },
636
+ run: async (command, faults) => {
637
+ for (const fault of faults) store.inject(fault); // e.g. fail the effect `markPaid`, or die after one effect
638
+ await (command.type === "pay" ? service.pay() : service.ship());
639
+ },
640
+ read: () => service.snapshot(),
641
+ };
642
+ await replayMachine(orderFlow, subject); // { status: "passed", replayed: 6, states: 3 }
643
+ ```
644
+
645
+ Where the machine and the code disagree the report is `failed` and `failure` holds the shortest sequence: `steps` with each command, the state the machine expected and the state the code answered, and a `reason` such as `After pay, ship, pay the machine reaches {"status":"shipped",...} but the subject reads {"status":"paid",...}`. A throw from `run` is accepted only where the machine does not run the command: where its `requires` precondition is false (a code that refuses with no change passes too, since the state is compared either way) or where an effect failed or the process died. Any other throw is a disagreement. An effect the machine fails, or a process death with `crashes: true`, is replayed too, and `faults` lists what to inject for the command (`{ kind: "fails", effect: "markPaid", index: 1, command, step: 0 }` or `{ kind: "dies", after: 1, command, step: 0 }`, where `step` is the place of `command` among the commands the run executed, 0 being the one replayed and the rest the ones it emitted); `faults: false` replays only the runs where every effect succeeds. A throw from `reset` or `read` reaches the caller, since the test harness is broken, not the code. `maxReplays` (default 10000), `maxStates`, `maxCommands`, `maxOutcomes` and `domainLimit` keep it bounded and leave the report `undetermined` when exceeded.
646
+
647
+
648
+ To fail CI unless the finite state check completes, export a machine and run:
649
+
650
+ ```sh
651
+ chisel model-check examples/order-machine.spec.ts
652
+ chisel model-check examples/order-machine.spec.ts --engine tla
653
+ chisel tla examples/order-machine.spec.ts --output-dir ./model
654
+ chisel prove-machine examples/open-machine.spec.ts
655
+ chisel model-check examples/order-machine.spec.ts --json --max-states 10000
656
+ chisel run-machine examples/order-machine.ts --state '{"phase":"draft","ordered":2,"received":0}' --command '{"type":"submit"}'
657
+ ```
658
+
659
+ `run-machine` returns the next state and all internal steps as JSON; it does not save them. When a module exports multiple machines, `--name` selects one for `run-machine`. `model-check` checks all exported machines by default and exits nonzero for `broken` or `undetermined`. Give multiple specifications of one machine distinct `name` values in `specifyMachine(machine, { name, invariants, transitions })` to select them with `--name`.
660
+
661
+ `--engine tla` also checks `requires` (a step whose precondition disagrees with whether it changes the state is a violation), and `prove-machine` proves each precondition as two obligations, one for "changes only if it holds" and one for "holds only if it changes". The matrix is produced by the native checker only. The proof compares object states field by field; any other value, such as a state that is a sum, an array field or a sum held in a field, is compared as a whole, which the prover may not discharge, so those obligations can stay `undetermined`.
662
+
663
+ `--engine tla` compiles the same expression-based update and invariant into a TLA+ `Step`, `Init`, and `Next` and checks them with `tla-ts`. It models emitted commands as a pending queue, so intermediate states are checked. `chisel tla` returns the module and config as JSON, or writes both `.tla` and `.cfg` files with `--output-dir`. TLA+ translation requires exhaustively enumerable state and command schemas and refuses unsupported operators instead of claiming a result. It reads `null` (as the empty set, which no other value a machine holds is), empty objects, field names TLA+ cannot spell (read by name, `s["foo-bar"]`), an array's `$length()`, and a supported `matchValue` or schema-preserving `map` (a direct array field of the state or command whose element and output are one schema, with a body that keeps to it) over a field held under its own schema; a `bind` or `map` of a field that may be left out is refused. For open state spaces the native `model-check` remains the available finite reachability check when commands can be enumerated; its result is `undetermined` if exploration does not complete. Existing output files are preserved; pass `--force` to replace both files. Use `--max-commands` to choose the generated command budget.
664
+
665
+ Before it checks anything, `--engine tla` (`checkMachineTla`) compares the translation with the TypeScript it came from. The states and the commands are finite and listed, so for every reachable state and every command the translated `Step` is evaluated by TLC and compared with what `evaluateCommand` reads off the machine (the state or the effects with their failure states, and the emitted commands), and the `StateDomain` and `CommandDomain` it lists with the ones TypeScript enumerates. The expected value is written by a renderer of its own, not the translator's, so a fault in how the translator writes a rule or a value shows as a pair that disagrees. A pair TypeScript refuses (an answer outside the schema) must not be accepted by the translation either. A translation that disagrees is `mismatch`, not `undetermined`, and nothing it says of the machine is relied on: the reason names the state and the command, what TypeScript gives and what the translation gives (`at state 1 and command true TypeScript gives [state |-> 2, commands |-> <<>>] and the translation [state |-> 1, commands |-> <<>>]`). The report's `validation` says how many pairs were compared (`{ status: "validated", pairs: 6, of: 6 }`); past `validationLimit` (`chisel model-check --validation-limit`, 20000 pairs by default, the largest machine tried compares 9,600 in under a second) a spread over all the pairs is compared and the status is `sampled`. `==` and `!=` on objects, arrays and null compare what they hold, as `deepEqual` does, in TypeScript and in TLA+ alike, and a state or command that holds a field `kind: "effect"` is no effect.
666
+
667
+ What TLA+ cannot take is refused before the check with what to change, and the result stays `undetermined`: an integer of 2^31 or more (TLC reads 32 bits), a string with a control character TLA+ has no escape for (anything below U+0020 except tab, newline, form feed and carriage return) or an unpaired surrogate, a sequence or a record with fields compared with null (null is the empty set there), `<`, `<=`, `>` or `>=` on an enum, a boolean or a string (TLA+ orders integers only), and a field of a command that may be left out (write the absence as a case of a sum), as for the state.
668
+
669
+ `prove-machine` emits universal inductive obligations for the initial states, the state contract, emitted commands, invariants, and transition properties, then calls tla-ts's proof engine. It reports `proved` only if every obligation is discharged. This can prove some machines with open state and command domains (see [`examples/open-machine.spec.ts`](examples/open-machine.spec.ts)); unsupported schema and expression constructs, or obligations the prover cannot discharge, remain `undetermined`. A proof is over the TLA+ interpretation of the supported expression subset; `runMachine` is still the executable implementation. Use `model-check` for counterexample traces and `prove-machine` for inductive claims.
670
+
671
+ `checkMachine` enumerates command values from their schema, then explores reachable states breadth first. A failing invariant or invalid state reports `broken` with the shortest *initial command sequence among explored paths* reaching it. An open command domain or a `maxStates` / `domainLimit` / `maxCommands` cutoff reports `undetermined`. `held` means all commands from the declared finite domain and all reachable states were checked. No claim is made about commands outside the schema or states outside the declared initial states. The reducer is built from Chisel terms and expressions; external dependency calls are refused. Emitted commands are internal transitions, not I/O. `runMachine` validates input and output schemas, while the verification tools check invariants and transition properties; `maxCommands` bounds recursive emissions. This executes the checked model itself without a separate runtime implementation. `world` and `explore` below remain useful when input domains cannot be enumerated, but their successful walks are samples.
672
+
673
+ ## Invariants a world keeps
674
+
675
+ Examples show that each behavior answers as its rows say. Some properties hold of a record only because the guards of several operations keep them together, and no single guard says so: a purchase order never receives more than it ordered because receiving checks what is open and changing the quantity checks what is received. Leave out either check and every example of each operation still passes, yet create, approve, issue, receive 3 of 8, then change the quantity to 2 reaches an order that has received more than it ordered.
676
+
677
+ A world declares the state its operations share, the states it starts from, the operations that move it, and what must hold of every state they reach, apart from the state's type: the type says what a state may hold, an invariant what a reachable state does hold.
678
+
679
+ ```ts
680
+ type State = c.Infer<typeof Orders>;
681
+ type Order = State["orders"][number];
682
+
683
+ const purchasing = c.world("purchasing", {
684
+ state: Orders,
685
+ initial: [{ orders: [] }],
686
+ operations: [
687
+ { implementation: creating, input: (state, draw) => ({ kind: "create", id: `po-${state.orders.length + 1}`, quantity: draw.int(1, 10) }), next: appended },
688
+ { implementation: receiving, input: (state, draw) => onOneOrder(draw.pick(state.orders), draw.int(1, 10)), next: replaced },
689
+ { implementation: counting, state: "state" },
690
+ ],
691
+ invariants: [
692
+ c.invariant<State>("no order receives more than it ordered", state => state.orders.$all(order => order.received.$lte(order.quantity))),
693
+ ],
694
+ transitions: [
695
+ c.transition<State>("no order is lost", (before, after) => after.orders.$length().$gte(before.orders.$length())),
696
+ c.transition<Order>("a closed order stays closed", { each: "orders", by: "id" }, (before, after) =>
697
+ before.status.$ne("CLOSED").$or(after.status.$eq("CLOSED"))),
698
+ ],
699
+ });
700
+
701
+ const report = await c.explore(purchasing, { runs: 100, steps: 20, seed: 1 });
702
+ ```
703
+
704
+ An invariant is a condition over the state, written with the term operators as a guard is, or a model expression answering a boolean when it needs `fold`, `bind` or `plus` to say; a transition relates the state before an operation to the state after it, as an action property `[][P]_vars` does in TLA+: a step that leaves the state as it was is not held to it. With `each` and `by`, a transition relates one record before and after: the records at the field `each` names are paired by their field `by` (or, in a record, by their keys), as `\A id : orders[id] … orders'[id]` pairs them in TLA+, and each pair that changed is held to it; a record only before or only after is not paired, so that one disappearing is said by a transition over the whole state. Keys are compared as values, so a key may be an object, and a step whose state before or after holds two records with one key breaks the transition, since it cannot tell which record became which. `world` refuses a transition whose `each` reaches no array or record of the state, or whose `by` the records do not declare, since it would find no pair and hold of every walk. A property of how a state may change can also be an invariant of a state that keeps its history (received quantities that equal the receipts recorded); a transition says what needs the change itself: a status the state machine has no arrow to, a field that changed without a revision, a posted record that disappeared. An operation either acts on the whole world, taking the state at the input field `state` names and answering the next one at the same field of its result (an answer without the field, a refusal, leaves the state as it was; one holding it, even as `null`, is checked as the next state; `world` refuses an operation whose input or result declares the field in no case; a sum's discriminant may be the field, the state then naming the input case it is handed to) while the rest of its input is drawn at random, or acts on part of it, such as one order, with `input` building its input from the state through `draw` (`pick`, `int`, `value` of a schema; undefined when there is nothing to act on) and `next` placing the answer back in the world. Both are handed a copy of the state, which they may change in place: the state before the step is kept for the transitions.
705
+
706
+ `explore` first checks every invariant of every starting state (a broken one is reported with no steps and `runs: 0`), then starts each of `runs` walks from one of the starting states and takes `steps` operations chosen at random, so it only ever checks states the operations reach. At every state it checks the state's type and every invariant, and across every step every transition. The report is `held`; `broken` with the invariant broken (or the operation that failed) and the steps from the starting state, each with its operation, input and the state before and after; or `undetermined` with a reason when nothing broke but an operation never ran (it had nothing to act on in any state reached, or no step chose it) or was reached where a case is still `todo` or implemented outside Chisel, since the walks said nothing about it. It says how often each operation ran, moved the state, had nothing to act on (`skipped`) and could not be run (`pending`). `runs` and `steps` must be positive integers. A broken walk is shortened before it is reported: each step records the random numbers it drew, and steps are dropped one at a time while the rest, replayed with their numbers, still break the same invariant. The same `seed`, an integer from 0 to 4294967295 (1 by default), draws the same walks. A walk that finds nothing is evidence, not a proof, as sampled successes never are.
707
+
390
708
  ## Composition
391
709
 
392
710
  `c.compose(name, [firstImplementation, secondImplementation, ...more])` connects behaviors the way Souther's `>->` does: of the cases a stage answers, those the next stage takes as input flow on to it, and the rest depart the main line and are answered as they are. It takes the stages' implementations and returns the composition's declaration and its implementation together.
@@ -463,3 +781,18 @@ For all three commands, `--behavior` matches the name passed to `behavior(...)`,
463
781
  Composition verification also checks forwarded results against the next stage's input contract. If that inclusion cannot be proved, the pipeline remains undetermined even when each stage verifies independently. `reportDocument` returns JSON-compatible values, including string representations of int64 witnesses and counterexamples.
464
782
 
465
783
  The [Souther comparison and design decisions](docs/souther-comparison.html) records the source revisions, changes and remaining differences.
784
+
785
+ ## Publishing
786
+
787
+ Versions are managed with [Changesets](https://github.com/changesets/changesets): a change that reaches the published package adds a changeset (`npm run changeset`). Before 1.0, a patch is any change that breaks nothing and a minor is a breaking change. On every push to `main`, the `release.yml` workflow opens or updates the `chore: release` pull request while changesets are pending; merging it publishes `@toiroakr/chisel` to npm, running the type check, tests and build through `prepublishOnly`, and creates the GitHub release.
788
+
789
+ Configure an npm Trusted Publisher for `@toiroakr/chisel` with:
790
+
791
+ - Provider: GitHub Actions
792
+ - Organization or user: `toiroakr`
793
+ - Repository: `chisel`
794
+ - Workflow filename: `release.yml`
795
+ - Environment name: `release`
796
+ - Permission: allow publishing
797
+
798
+ The workflow authenticates with OIDC and publishes provenance; no npm token secret is required.