@toiroakr/chisel 0.1.0 → 0.2.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 (109) hide show
  1. package/README.md +249 -20
  2. package/dist/absence.d.ts +27 -0
  3. package/dist/absence.js +228 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +21 -9
  6. package/dist/behavior.js +219 -52
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/border.d.ts +4 -7
  9. package/dist/border.js +43 -35
  10. package/dist/border.js.map +1 -1
  11. package/dist/bounds.d.ts +1 -0
  12. package/dist/bounds.js +26 -0
  13. package/dist/bounds.js.map +1 -0
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +272 -4
  16. package/dist/cli.js.map +1 -1
  17. package/dist/codec.js +7 -4
  18. package/dist/codec.js.map +1 -1
  19. package/dist/codegen.js +4 -8
  20. package/dist/codegen.js.map +1 -1
  21. package/dist/composition.d.ts +3 -3
  22. package/dist/composition.js +4 -4
  23. package/dist/composition.js.map +1 -1
  24. package/dist/data.d.ts +1 -0
  25. package/dist/data.js +2 -0
  26. package/dist/data.js.map +1 -1
  27. package/dist/dependency.d.ts +9 -6
  28. package/dist/dependency.js +23 -17
  29. package/dist/dependency.js.map +1 -1
  30. package/dist/domain.d.ts +5 -1
  31. package/dist/domain.js +6 -6
  32. package/dist/domain.js.map +1 -1
  33. package/dist/ensures.js +2 -2
  34. package/dist/ensures.js.map +1 -1
  35. package/dist/equal.d.ts +1 -0
  36. package/dist/equal.js +135 -0
  37. package/dist/equal.js.map +1 -0
  38. package/dist/feasibility.d.ts +5 -3
  39. package/dist/feasibility.js +106 -37
  40. package/dist/feasibility.js.map +1 -1
  41. package/dist/guard-borders.d.ts +12 -5
  42. package/dist/guard-borders.js +122 -171
  43. package/dist/guard-borders.js.map +1 -1
  44. package/dist/guard-scope.d.ts +61 -0
  45. package/dist/guard-scope.js +364 -0
  46. package/dist/guard-scope.js.map +1 -0
  47. package/dist/index.d.ts +17 -6
  48. package/dist/index.js +8 -3
  49. package/dist/index.js.map +1 -1
  50. package/dist/interleave.d.ts +31 -0
  51. package/dist/interleave.js +202 -0
  52. package/dist/interleave.js.map +1 -0
  53. package/dist/interval.d.ts +7 -0
  54. package/dist/interval.js +171 -21
  55. package/dist/interval.js.map +1 -1
  56. package/dist/isolated.js.map +1 -1
  57. package/dist/machine-check.d.ts +73 -0
  58. package/dist/machine-check.js +215 -0
  59. package/dist/machine-check.js.map +1 -0
  60. package/dist/machine.d.ts +97 -0
  61. package/dist/machine.js +200 -0
  62. package/dist/machine.js.map +1 -0
  63. package/dist/model.d.ts +74 -9
  64. package/dist/model.js +469 -34
  65. package/dist/model.js.map +1 -1
  66. package/dist/outcomes.d.ts +7 -0
  67. package/dist/outcomes.js +38 -0
  68. package/dist/outcomes.js.map +1 -0
  69. package/dist/pairs.js +12 -4
  70. package/dist/pairs.js.map +1 -1
  71. package/dist/partition.d.ts +1 -0
  72. package/dist/partition.js +90 -11
  73. package/dist/partition.js.map +1 -1
  74. package/dist/proof.d.ts +6 -0
  75. package/dist/proof.js +96 -22
  76. package/dist/proof.js.map +1 -1
  77. package/dist/replay.d.ts +45 -0
  78. package/dist/replay.js +157 -0
  79. package/dist/replay.js.map +1 -0
  80. package/dist/rule.d.ts +47 -7
  81. package/dist/rule.js +284 -17
  82. package/dist/rule.js.map +1 -1
  83. package/dist/runtime.d.ts +12 -0
  84. package/dist/runtime.js +8 -0
  85. package/dist/runtime.js.map +1 -0
  86. package/dist/schema.js +16 -12
  87. package/dist/schema.js.map +1 -1
  88. package/dist/specification.d.ts +12 -2
  89. package/dist/specification.js +622 -82
  90. package/dist/specification.js.map +1 -1
  91. package/dist/temporal-global.d.ts +4 -0
  92. package/dist/temporal-global.js +11 -0
  93. package/dist/temporal-global.js.map +1 -0
  94. package/dist/temporal.d.ts +22 -0
  95. package/dist/temporal.js +113 -0
  96. package/dist/temporal.js.map +1 -0
  97. package/dist/tla.d.ts +54 -0
  98. package/dist/tla.js +579 -0
  99. package/dist/tla.js.map +1 -0
  100. package/dist/verification.d.ts +7 -0
  101. package/dist/verification.js +5 -0
  102. package/dist/verification.js.map +1 -0
  103. package/dist/ways.d.ts +8 -5
  104. package/dist/ways.js +30 -39
  105. package/dist/ways.js.map +1 -1
  106. package/dist/world.d.ts +98 -0
  107. package/dist/world.js +467 -0
  108. package/dist/world.js.map +1 -0
  109. package/package.json +32 -9
package/README.md CHANGED
@@ -1,28 +1,33 @@
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`; 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
+ **0.2.0 migration:** The package root now exports the state-machine runtime. Existing 0.1.x imports of `behavior`, `spec`, `check`, and related APIs must change from `@toiroakr/chisel` to `@toiroakr/chisel/full`. Verification of machines uses `@toiroakr/chisel/verification`. This breaking export change is outside the `^0.1.0` version range.
18
+
19
+ The earlier behavior-and-example workflow remains available from `/full` and is documented below.
17
20
 
18
21
  ## 1. Declare data and behavior
19
22
 
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.
23
+ The behavior and specification examples below use `import * as c from "@toiroakr/chisel/full"`. The package root `@toiroakr/chisel` provides the executable state-machine API described in [one reducer for runtime and exhaustive checking](#one-reducer-for-runtime-and-exhaustive-checking), together with what production code needs to run a behavior: the schemas, `behavior`, `implement`, `model` and its expressions, `dependency`, `perform`, `performSync`, `decode` and `encode`. It reaches neither the analysis (`check`, `generate`, `verify`) nor zod, tsx or `tla-ts`, so code that runs a verified model in place of its own imports only the root, and its specification imports `/full` alongside.
24
+
25
+ `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
26
 
22
27
  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
28
 
24
29
  ```ts
25
- import * as c from "@toiroakr/chisel";
30
+ import * as c from "@toiroakr/chisel/full";
26
31
 
27
32
  const Order = c.variants("state", {
28
33
  unpaid: c.object({ orderId: c.string() }),
@@ -185,7 +190,7 @@ npm run example:verified
185
190
 
186
191
  `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
192
 
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.
193
+ 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
194
 
190
195
  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
196
 
@@ -200,7 +205,7 @@ const pricing = c.behavior("pricing", {
200
205
  }),
201
206
  result: c.int().min(1).max(101),
202
207
  effects: c.variants("kind", {}),
203
- requires: {
208
+ dependencies: {
204
209
  price: c.dependency(c.int().min(1).max(100), c.int().min(0).max(100)),
205
210
  },
206
211
  });
@@ -219,6 +224,8 @@ The verifier proves each argument satisfies the dependency's input contract and
219
224
 
220
225
  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
226
 
227
+ 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.
228
+
222
229
  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
230
 
224
231
  ### Local values and collections
@@ -245,6 +252,20 @@ const result = c.matchValue(answer, c.call(deps.lookup, input), {
245
252
  });
246
253
  ```
247
254
 
255
+ 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`.
256
+
257
+ ### Absence is a case of a sum
258
+
259
+ 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.
260
+
261
+ ```ts
262
+ const label = c.variants("state", { absent: c.object({}), given: c.object({ value: c.string().min(1) }) });
263
+ const result = c.matchValue(label, input.name, {
264
+ absent: () => ({ verdict: "none" }),
265
+ given: name => ({ verdict: "owner", name: name.value }),
266
+ });
267
+ ```
268
+
248
269
  `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
270
 
250
271
  ```ts
@@ -262,12 +283,12 @@ These builders run at declaration time; the interpreter executes the resulting e
262
283
 
263
284
  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
285
 
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.
286
+ 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
287
 
267
288
 
268
289
  ## Commands
269
290
 
270
- Chisel requires Node.js 26 or later and uses its built-in Temporal API.
291
+ 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
292
 
272
293
  ```sh
273
294
  npm install
@@ -285,6 +306,8 @@ node dist/cli.js check ./cancel-order.spec.ts --strict
285
306
 
286
307
  `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
308
 
309
+ 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.
310
+
288
311
  ## Progressive demo
289
312
 
290
313
  The [hotel reservation demo](./examples/progressive-demo/README.md) runs the complete declaration → generation → human answer → refinement → implementation sequence.
@@ -304,11 +327,26 @@ The analyzer follows the example-adequacy model of [Souther](https://github.com/
304
327
 
305
328
  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
329
 
330
+ 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:
331
+
332
+ ```ts
333
+ c.model("plan the receipt", order => ({
334
+ result: {
335
+ outcome: "planned",
336
+ expectedOn: c.plus(order.exFactoryOn, order.leadTimeDays, "days"),
337
+ daysLate: c.between(order.exFactoryOn, order.completedOn, "days"),
338
+ },
339
+ effects: [],
340
+ }))
341
+ ```
342
+
343
+ 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.
344
+
307
345
  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
346
 
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.
347
+ 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
348
 
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.
349
+ 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
350
 
313
351
  ```ts
314
352
  const Line = c.object({
@@ -321,7 +359,7 @@ const SubtotalByProduct = c.record(c.int().min(0)).min(1);
321
359
 
322
360
  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
361
 
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:
362
+ - **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
363
 
326
364
  ```ts
327
365
  const implementation = c.implement(checkout, {
@@ -350,7 +388,7 @@ A behavior can state what it ensures of its answer, and declare the outside worl
350
388
  ```ts
351
389
  const findMember = c.behavior("find-member", {
352
390
  input, result, effects,
353
- requires: { now: c.dependency(c.instant()), lookup: c.dependency(c.string(), c.boolean()) },
391
+ dependencies: { now: c.dependency(c.instant()), lookup: c.dependency(c.string(), c.boolean()) },
354
392
  ensures: clause => [
355
393
  clause.when("a found member is the one asked for", ["found"], (asked, answer) =>
356
394
  asked.id.$gt(0).$and(answer.id.$eq(asked.id)),
@@ -359,7 +397,7 @@ const findMember = c.behavior("find-member", {
359
397
  });
360
398
  ```
361
399
 
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).
400
+ 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
401
 
364
402
  `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
403
 
@@ -387,6 +425,182 @@ c.implement(approve, {
387
425
 
388
426
  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
427
 
428
+ ## One reducer for runtime and exhaustive checking
429
+
430
+ 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`; 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. The optional `/runtime` subpath is an alias of the root, which also exports the behavior runtime described above; the previous combined API is available from `/full`.
431
+
432
+ ```ts
433
+ import * as c from "@toiroakr/chisel";
434
+
435
+ const State = c.int().min(0).max(2);
436
+ const Command = c.enum(["go", "finish"] as const);
437
+ export const workflow = c.machine("two steps", {
438
+ state: State,
439
+ command: Command,
440
+ initial: [0],
441
+ update: (state, command) => ({
442
+ state: c.choose(state.$lt(2), state.$plus(1), state),
443
+ commands: c.choose(command.$eq("go"), ["finish" as const], [] as const),
444
+ }),
445
+ });
446
+
447
+ c.runMachine(workflow, 0, "go"); // { state: 2, steps: [go: 0→1, finish: 1→2] }
448
+ ```
449
+
450
+ In a separate `workflow.spec.ts` file used by CI:
451
+
452
+ ```ts
453
+ import { invariant, specifyMachine, checkMachine } from "@toiroakr/chisel/verification";
454
+ import { workflow } from "./workflow.js";
455
+
456
+ export const specification = specifyMachine(workflow, {
457
+ invariants: [invariant<number>("at most two", state => state.$lte(2))],
458
+ });
459
+ checkMachine(specification); // { status: "held", states: 3, transitions: 6 }
460
+ ```
461
+
462
+ [`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.
463
+
464
+ `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.
465
+
466
+ `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.
467
+
468
+ 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.
469
+
470
+ ```ts
471
+ update: (state, command) => ({
472
+ effects: [
473
+ c.effect("writeLabel", { ...state, label: "in-progress" }),
474
+ c.effect("runScript", { ...state, migrated: true }),
475
+ c.effect("writeLabel", { ...state, label: "checkpoint" }),
476
+ ],
477
+ }),
478
+ ```
479
+
480
+ `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.
481
+
482
+ 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:
483
+
484
+ ```ts
485
+ import * as c from "@toiroakr/chisel";
486
+ import { invariant, specifyMachine, checkMachine } from "@toiroakr/chisel/verification";
487
+
488
+ const checkout = c.machine("checkout", {
489
+ state: c.object({ reserved: c.boolean(), charged: c.boolean() }),
490
+ command: c.enum(["checkout"]), initial: [{ reserved: false, charged: false }],
491
+ update: state => ({
492
+ effects: [
493
+ c.effect("reserve", { reserved: true, charged: state.charged }, { failure: state }),
494
+ c.effect("charge", { reserved: true, charged: true }, { failure: state }),
495
+ ],
496
+ }),
497
+ });
498
+ const leak = invariant("a reservation is never left unpaid", state => state.reserved.$eq(false).$or(state.charged.$eq(true)));
499
+ checkMachine(specifyMachine(checkout, { invariants: [leak] })); // held
500
+ checkMachine(specifyMachine(checkout, { invariants: [leak], crashes: true })); // broken: checkout died after effect 1 (reserve)
501
+ ```
502
+
503
+ 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.
504
+
505
+ 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:
506
+
507
+ ```ts
508
+ const shop = c.machine("shop", {
509
+ state: c.object({ stock: c.int().min(0).max(1), a: c.boolean(), b: c.boolean() }),
510
+ command: c.variants("type", { buy: c.object({ customer: c.enum(["a", "b"]) }) }),
511
+ initial: [{ stock: 1, a: false, b: false }],
512
+ update: (state, command) => ({
513
+ effects: c.choose(state.stock.$gte(1), [
514
+ c.effect("take", {
515
+ stock: state.stock.$minus(1),
516
+ a: c.choose(command.customer.$eq("a"), true, state.a),
517
+ b: c.choose(command.customer.$eq("b"), true, state.b),
518
+ }, { ifUnchanged: true }), // drop the option to see the lost update
519
+ ], []),
520
+ }),
521
+ });
522
+ const once = invariant("the last unit is sold once", state => state.a.$eq(false).$or(state.b.$eq(false)));
523
+ const specification = specifyMachine(shop, { invariants: [once] });
524
+ checkInterleavings(specification, { copies: [{ type: "buy", customer: "a" }, { type: "buy", customer: "b" }] });
525
+ // held; terminals: finished/refused, refused/finished, and the sequential finished/finished
526
+ ```
527
+
528
+ 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.
529
+
530
+ 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:
531
+
532
+ ```ts
533
+ let store, service;
534
+ const subject = {
535
+ reset: state => { store = fakeStore(state); service = new OrderService(store); },
536
+ run: async (command, faults) => {
537
+ for (const fault of faults) store.inject(fault); // e.g. fail the effect `markPaid`, or die after one effect
538
+ await (command.type === "pay" ? service.pay() : service.ship());
539
+ },
540
+ read: () => service.snapshot(),
541
+ };
542
+ await replayMachine(orderFlow, subject); // { status: "passed", replayed: 6, states: 3 }
543
+ ```
544
+
545
+ 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.
546
+
547
+
548
+ To fail CI unless the finite state check completes, export a machine and run:
549
+
550
+ ```sh
551
+ chisel model-check examples/order-machine.spec.ts
552
+ chisel model-check examples/order-machine.spec.ts --engine tla
553
+ chisel tla examples/order-machine.spec.ts --output-dir ./model
554
+ chisel prove-machine examples/open-machine.spec.ts
555
+ chisel model-check examples/order-machine.spec.ts --json --max-states 10000
556
+ chisel run-machine examples/order-machine.ts --state '{"phase":"draft","ordered":2,"received":0}' --command '{"type":"submit"}'
557
+ ```
558
+
559
+ `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`.
560
+
561
+ `--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`.
562
+
563
+ `--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. 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.
564
+
565
+ `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.
566
+
567
+ `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.
568
+
569
+ ## Invariants a world keeps
570
+
571
+ 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.
572
+
573
+ 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.
574
+
575
+ ```ts
576
+ type State = c.Infer<typeof Orders>;
577
+ type Order = State["orders"][number];
578
+
579
+ const purchasing = c.world("purchasing", {
580
+ state: Orders,
581
+ initial: [{ orders: [] }],
582
+ operations: [
583
+ { implementation: creating, input: (state, draw) => ({ kind: "create", id: `po-${state.orders.length + 1}`, quantity: draw.int(1, 10) }), next: appended },
584
+ { implementation: receiving, input: (state, draw) => onOneOrder(draw.pick(state.orders), draw.int(1, 10)), next: replaced },
585
+ { implementation: counting, state: "state" },
586
+ ],
587
+ invariants: [
588
+ c.invariant<State>("no order receives more than it ordered", state => state.orders.$all(order => order.received.$lte(order.quantity))),
589
+ ],
590
+ transitions: [
591
+ c.transition<State>("no order is lost", (before, after) => after.orders.$length().$gte(before.orders.$length())),
592
+ c.transition<Order>("a closed order stays closed", { each: "orders", by: "id" }, (before, after) =>
593
+ before.status.$ne("CLOSED").$or(after.status.$eq("CLOSED"))),
594
+ ],
595
+ });
596
+
597
+ const report = await c.explore(purchasing, { runs: 100, steps: 20, seed: 1 });
598
+ ```
599
+
600
+ 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.
601
+
602
+ `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.
603
+
390
604
  ## Composition
391
605
 
392
606
  `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 +677,18 @@ For all three commands, `--behavior` matches the name passed to `behavior(...)`,
463
677
  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
678
 
465
679
  The [Souther comparison and design decisions](docs/souther-comparison.html) records the source revisions, changes and remaining differences.
680
+
681
+ ## Publishing
682
+
683
+ The `release.yml` workflow publishes `@toiroakr/chisel` when a `v*` tag is pushed. The tag must match the version in `package.json` (for example, `v0.2.0` for version `0.2.0`). Publishing runs the type check, tests, and build through `prepublishOnly`. The workflow can also be rerun manually by selecting the release tag.
684
+
685
+ Configure an npm Trusted Publisher for `@toiroakr/chisel` with:
686
+
687
+ - Provider: GitHub Actions
688
+ - Organization or user: `toiroakr`
689
+ - Repository: `chisel`
690
+ - Workflow filename: `release.yml`
691
+ - Environment name: leave empty
692
+ - Permission: allow publishing
693
+
694
+ The workflow authenticates with OIDC and publishes provenance; no npm token secret is required.
@@ -0,0 +1,27 @@
1
+ import type { ElementLabels, Rule } from "./rule.js";
2
+ import type { AnySchema, VariantTable } from "./schema.js";
3
+ export interface Fact {
4
+ readonly rule: Rule;
5
+ readonly outcome: boolean;
6
+ }
7
+ export interface Roots {
8
+ readonly scope: AnySchema;
9
+ readonly locals?: ReadonlyMap<string, AnySchema>;
10
+ readonly labels?: ElementLabels;
11
+ readonly declared?: ReadonlySet<string>;
12
+ readonly input?: {
13
+ readonly sum: {
14
+ readonly discriminant: string;
15
+ readonly variants: VariantTable;
16
+ };
17
+ readonly tag: string;
18
+ };
19
+ }
20
+ export declare function factsOf(rule: Rule, outcome: boolean): readonly Fact[];
21
+ export declare function leftOutReadIn(rule: Rule, roots: Roots, facts?: readonly Fact[], label?: string): string | undefined;
22
+ export declare function choiceFacts(template: unknown): ReadonlyMap<unknown, readonly Fact[]>;
23
+ export declare function casesLeft(sum: {
24
+ readonly discriminant: string;
25
+ readonly variants: VariantTable;
26
+ }, at: readonly string[], facts: readonly Fact[]): readonly string[];
27
+ export declare function leftOutReadInModel(template: unknown, roots: Roots, facts?: readonly Fact[]): string | undefined;