@typeonce/effect-machine 0.45.1 → 0.47.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 (148) hide show
  1. package/AGENTS.md +1823 -0
  2. package/CLAUDE.md +1823 -0
  3. package/README.md +100 -77
  4. package/ai-docs/README.md +18 -0
  5. package/ai-docs/src/10_modeling/01_create-a-machine.ts +51 -0
  6. package/ai-docs/src/10_modeling/02_branch-on-an-event.ts +55 -0
  7. package/ai-docs/src/10_modeling/03_update-retained-state.ts +58 -0
  8. package/ai-docs/src/10_modeling/04_verify-after-changing.ts +29 -0
  9. package/{docs/agent-guide.md → ai-docs/src/10_modeling/index.md} +254 -155
  10. package/{docs/root-api.md → ai-docs/src/20_root-api/index.md} +29 -57
  11. package/{docs/effect-atom-react.md → ai-docs/src/30_react/index.md} +49 -49
  12. package/{docs/machine-review.md → ai-docs/src/40_review/index.md} +42 -40
  13. package/ai-docs/src/index.md +7 -0
  14. package/ai-docs/tsconfig.json +22 -0
  15. package/dist/Machine.d.ts +1205 -1478
  16. package/dist/Machine.d.ts.map +1 -1
  17. package/dist/Machine.js +366 -214
  18. package/dist/Machine.js.map +1 -1
  19. package/dist/internal/machine/atom.js.map +1 -1
  20. package/dist/internal/machine/cluster.js.map +1 -1
  21. package/dist/internal/machine/command.d.ts +8 -0
  22. package/dist/internal/machine/command.d.ts.map +1 -1
  23. package/dist/internal/machine/command.js +2 -2
  24. package/dist/internal/machine/command.js.map +1 -1
  25. package/dist/internal/machine/configuration.d.ts +21 -5
  26. package/dist/internal/machine/configuration.d.ts.map +1 -1
  27. package/dist/internal/machine/configuration.js +1 -0
  28. package/dist/internal/machine/configuration.js.map +1 -1
  29. package/dist/internal/machine/construction.js.map +1 -1
  30. package/dist/internal/machine/declaration.d.ts +2 -1
  31. package/dist/internal/machine/declaration.d.ts.map +1 -1
  32. package/dist/internal/machine/declaration.js +28 -46
  33. package/dist/internal/machine/declaration.js.map +1 -1
  34. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  35. package/dist/internal/machine/executionPlan.js +23 -16
  36. package/dist/internal/machine/executionPlan.js.map +1 -1
  37. package/dist/internal/machine/implementation.d.ts +2 -0
  38. package/dist/internal/machine/implementation.d.ts.map +1 -1
  39. package/dist/internal/machine/implementation.js.map +1 -1
  40. package/dist/internal/machine/initialDeclaration.d.ts +2 -0
  41. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  42. package/dist/internal/machine/initialDeclaration.js +15 -0
  43. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  44. package/dist/internal/machine/invocation.d.ts.map +1 -1
  45. package/dist/internal/machine/invocation.js +32 -21
  46. package/dist/internal/machine/invocation.js.map +1 -1
  47. package/dist/internal/machine/invocationEvent.d.ts +34 -17
  48. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  49. package/dist/internal/machine/invocationEvent.js +16 -4
  50. package/dist/internal/machine/invocationEvent.js.map +1 -1
  51. package/dist/internal/machine/machine.d.ts +5 -22
  52. package/dist/internal/machine/machine.d.ts.map +1 -1
  53. package/dist/internal/machine/machine.js +157 -119
  54. package/dist/internal/machine/machine.js.map +1 -1
  55. package/dist/internal/machine/planner.d.ts +15 -4
  56. package/dist/internal/machine/planner.d.ts.map +1 -1
  57. package/dist/internal/machine/planner.js +18 -21
  58. package/dist/internal/machine/planner.js.map +1 -1
  59. package/dist/internal/machine/process.d.ts +2 -0
  60. package/dist/internal/machine/process.d.ts.map +1 -1
  61. package/dist/internal/machine/process.js +2 -0
  62. package/dist/internal/machine/process.js.map +1 -1
  63. package/dist/internal/machine/protocol.js.map +1 -1
  64. package/dist/internal/machine/runtime.d.ts.map +1 -1
  65. package/dist/internal/machine/runtime.js.map +1 -1
  66. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  67. package/dist/internal/machine/runtimeGeneric.js +5 -3
  68. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  69. package/dist/internal/machine/runtimeProtocol.d.ts +26 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  71. package/dist/internal/machine/runtimeProtocol.js +71 -0
  72. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  73. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  74. package/dist/internal/machine/stateDefinition.js +0 -14
  75. package/dist/internal/machine/stateDefinition.js.map +1 -1
  76. package/dist/internal/machine/symbols.d.ts +9 -0
  77. package/dist/internal/machine/symbols.d.ts.map +1 -1
  78. package/dist/internal/machine/symbols.js.map +1 -1
  79. package/dist/internal/machine/topology.d.ts +18 -9
  80. package/dist/internal/machine/topology.d.ts.map +1 -1
  81. package/dist/internal/machine/topology.js +16 -1
  82. package/dist/internal/machine/topology.js.map +1 -1
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  84. package/dist/internal/testing/machine/arbitrary.js +2 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  86. package/dist/internal/testing/machine/check.d.ts +17 -0
  87. package/dist/internal/testing/machine/check.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/check.js +371 -0
  89. package/dist/internal/testing/machine/check.js.map +1 -0
  90. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/exploration.js.map +1 -1
  92. package/dist/internal/testing/machine/finiteModel.d.ts +14 -13
  93. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  94. package/dist/internal/testing/machine/finiteModel.js +21 -23
  95. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  96. package/dist/internal/testing/machine/runtime.d.ts +19 -88
  97. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  98. package/dist/internal/testing/machine/runtime.js +0 -19
  99. package/dist/internal/testing/machine/runtime.js.map +1 -1
  100. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -1
  101. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  102. package/dist/internal/testing/machine/verification.js.map +1 -1
  103. package/dist/testing/MachineTest.d.ts +349 -139
  104. package/dist/testing/MachineTest.d.ts.map +1 -1
  105. package/dist/testing/MachineTest.js +201 -136
  106. package/dist/testing/MachineTest.js.map +1 -1
  107. package/dist/unstable/cluster/ClusterMachine.d.ts +9 -14
  108. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  109. package/dist/unstable/cluster/ClusterMachine.js +9 -14
  110. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  111. package/dist/unstable/reactivity/AtomMachine.d.ts +169 -80
  112. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  113. package/dist/unstable/reactivity/AtomMachine.js +165 -76
  114. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  115. package/package.json +11 -9
  116. package/src/Machine.ts +1149 -2134
  117. package/src/internal/machine/atom.ts +3 -3
  118. package/src/internal/machine/cluster.ts +2 -2
  119. package/src/internal/machine/command.ts +10 -4
  120. package/src/internal/machine/configuration.ts +16 -17
  121. package/src/internal/machine/construction.ts +1 -1
  122. package/src/internal/machine/declaration.ts +25 -50
  123. package/src/internal/machine/executionPlan.ts +90 -56
  124. package/src/internal/machine/implementation.ts +3 -1
  125. package/src/internal/machine/initialDeclaration.ts +16 -0
  126. package/src/internal/machine/invocation.ts +73 -70
  127. package/src/internal/machine/invocationEvent.ts +46 -20
  128. package/src/internal/machine/machine.ts +217 -243
  129. package/src/internal/machine/planner.ts +72 -106
  130. package/src/internal/machine/process.ts +12 -0
  131. package/src/internal/machine/protocol.ts +6 -6
  132. package/src/internal/machine/runtime.ts +1 -5
  133. package/src/internal/machine/runtimeCompiled.ts +2 -2
  134. package/src/internal/machine/runtimeGeneric.ts +7 -7
  135. package/src/internal/machine/runtimeProtocol.ts +80 -4
  136. package/src/internal/machine/stateDefinition.ts +0 -39
  137. package/src/internal/machine/symbols.ts +11 -0
  138. package/src/internal/machine/topology.ts +40 -18
  139. package/src/internal/testing/machine/arbitrary.ts +2 -0
  140. package/src/internal/testing/machine/check.ts +460 -0
  141. package/src/internal/testing/machine/exploration.ts +4 -5
  142. package/src/internal/testing/machine/finiteModel.ts +40 -42
  143. package/src/internal/testing/machine/runtime.ts +31 -170
  144. package/src/internal/testing/machine/runtimeInvariant.ts +3 -3
  145. package/src/internal/testing/machine/verification.ts +14 -14
  146. package/src/testing/MachineTest.ts +366 -145
  147. package/src/unstable/cluster/ClusterMachine.ts +9 -14
  148. package/src/unstable/reactivity/AtomMachine.ts +167 -78
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Static model analysis and the one-call machine check composed from it,
3
+ * bounded exploration, coverage, and the planner verification laws.
4
+ *
5
+ * @since 0.47.0
6
+ */
7
+
8
+ import * as Arbitrary from "effect/Arbitrary"
9
+ import * as Cause from "effect/Cause"
10
+ import * as Effect from "effect/Effect"
11
+ import * as Exit from "effect/Exit"
12
+ import * as Schema from "effect/Schema"
13
+ import * as Machine from "../../../Machine.js"
14
+ import type {
15
+ AnalysisFinding,
16
+ CheckExplorationLimit,
17
+ CheckFinding,
18
+ CheckOptions,
19
+ CheckReplay,
20
+ CheckReport,
21
+ EventPlan,
22
+ ExplorationEdge,
23
+ ExplorationNode,
24
+ InitialPlan,
25
+ RunFailure,
26
+ RunServices,
27
+ Trace,
28
+ TraceStep
29
+ } from "../../../testing/MachineTest.js"
30
+ import * as Protocol from "../../machine/protocol.js"
31
+ import type { EnsureExecutable } from "../../machine/readiness.js"
32
+ import { explore } from "./exploration.js"
33
+ import { formatValue } from "./format.js"
34
+ import { InvariantError } from "./invariant.js"
35
+ import { VerificationError, verify } from "./verification.js"
36
+
37
+ type AnyMachine = Machine.Machine.Any
38
+
39
+ type ReadyMachine<M extends AnyMachine> =
40
+ & M
41
+ & EnsureExecutable<
42
+ Machine.Machine.States<M>,
43
+ Machine.Machine.UnhandledStates<M>,
44
+ Machine.Machine.OutputStates<M>
45
+ >
46
+
47
+ const defaultLimits = { maxDepth: 16, maxStates: 256, maxTransitions: 2_048 }
48
+
49
+ const isDescendant = (path: string, ancestor: string): boolean =>
50
+ ancestor === "" ? path !== "" : path.startsWith(`${ancestor}.`)
51
+
52
+ const reachableStatePaths = (machine: AnyMachine): ReadonlySet<string> => {
53
+ const nodes = Machine.stateNodes(machine)
54
+ const byPath = new Map<string, (typeof nodes)[number]>(nodes.map((node) => [node.path, node]))
55
+ const definitions = Machine.transitionDefinitions(machine)
56
+ const reached = new Set<string>()
57
+ const entered = new Set<string>()
58
+ const queue: Array<string> = []
59
+
60
+ const mark = (path: string): void => {
61
+ let current = byPath.get(path)
62
+ while (current !== undefined) {
63
+ if (!reached.has(current.path)) {
64
+ reached.add(current.path)
65
+ queue.push(current.path)
66
+ }
67
+ current = current.parent === undefined ? undefined : byPath.get(current.parent)
68
+ }
69
+ }
70
+ // A resolver can construct any explicit descendant of a branch target, and a
71
+ // history default any descendant of its owner. Treating those subtrees as
72
+ // entered keeps the analysis conservative: it never reports a live state.
73
+ const enterSubtree = (path: string): void => {
74
+ for (const node of nodes) {
75
+ if (node.path === path || isDescendant(node.path, path)) enter(node.path)
76
+ }
77
+ }
78
+ const enter = (path: string): void => {
79
+ const node = byPath.get(path)
80
+ if (node === undefined) return
81
+ mark(path)
82
+ if (entered.has(path)) return
83
+ entered.add(path)
84
+ if (node.type === "parallel") {
85
+ for (const child of nodes) {
86
+ if (child.parent === path && child.type !== "history" && child.type !== "choice") enter(child.path)
87
+ }
88
+ } else if (node.type === "compound" && node.initial !== undefined) {
89
+ enter(node.initial)
90
+ } else if (node.type === "history" && node.parent !== undefined) {
91
+ enterSubtree(node.parent)
92
+ }
93
+ }
94
+
95
+ enter(Machine.initialDefinition(machine).target)
96
+ for (let index = 0; index < queue.length; index++) {
97
+ const source = queue[index]!
98
+ for (const definition of definitions) {
99
+ if (definition.source !== source) continue
100
+ for (const branch of definition.branches) {
101
+ if (branch.target === undefined) continue
102
+ if (branch.type === "branch") enterSubtree(branch.target)
103
+ else enter(branch.target)
104
+ }
105
+ }
106
+ }
107
+ return reached
108
+ }
109
+
110
+ export const analyze = (machine: AnyMachine): ReadonlyArray<AnalysisFinding> => {
111
+ const findings: Array<AnalysisFinding> = []
112
+
113
+ const handled = new Set<PropertyKey>()
114
+ for (const { trigger } of Machine.transitionDefinitions(machine)) {
115
+ if (trigger.type === "event") handled.add(trigger.event)
116
+ }
117
+ for (const event of Reflect.ownKeys(machine.events)) {
118
+ if (handled.has(event)) continue
119
+ findings.push({
120
+ law: "events.noHandler",
121
+ severity: "error",
122
+ event: String(event),
123
+ message: `Public event "${String(event)}" has no handler in any state. Handle it, or remove it from the protocol.`
124
+ })
125
+ }
126
+
127
+ const nodes = Machine.stateNodes(machine)
128
+ const reached = reachableStatePaths(machine)
129
+ const unreachable = nodes.filter((node) => !reached.has(node.path))
130
+ for (const node of unreachable) {
131
+ // A descendant of an unreachable state adds no new information.
132
+ if (unreachable.some((other) => isDescendant(node.path, other.path))) continue
133
+ findings.push({
134
+ law: "topology.noPathFromInitial",
135
+ severity: "error",
136
+ path: node.path,
137
+ descendants: unreachable.filter((other) => isDescendant(other.path, node.path)).length,
138
+ message: `State "${node.path}" has no declared path from the initial state. ` +
139
+ `Add a transition that targets it, or remove it.`
140
+ })
141
+ }
142
+ return findings
143
+ }
144
+
145
+ interface DerivedEvents {
146
+ readonly events: ReadonlyArray<unknown>
147
+ readonly enumerated: boolean
148
+ }
149
+
150
+ const deriveEvents = (machine: AnyMachine, seed: number, perTag: number) =>
151
+ Effect.gen(function*() {
152
+ const selected = new Map<PropertyKey, Map<string, unknown>>()
153
+ let enumerated = true
154
+ for (const [index, schema] of Protocol.inputEventSchemas(machine).entries()) {
155
+ const samples = yield* Arbitrary.sampleEffect(Arbitrary.schema(schema), {
156
+ count: Math.max(64, perTag * 16),
157
+ seed: seed + index
158
+ })
159
+ for (const sample of samples) {
160
+ const event = sample
161
+ if (Reflect.ownKeys(event).some((key) => key !== "_tag")) enumerated = false
162
+ const values = selected.get(event._tag) ?? new Map<string, unknown>()
163
+ const key = formatValue(event)
164
+ if (!values.has(key) && values.size < perTag) values.set(key, event)
165
+ selected.set(event._tag, values)
166
+ }
167
+ }
168
+ // A union may not sample every member. Report that as incomplete rather than guessing.
169
+ if (Reflect.ownKeys(machine.events).some((tag) => !selected.has(tag))) enumerated = false
170
+ return {
171
+ events: [...selected.values()].flatMap((values) => [...values.values()]),
172
+ enumerated
173
+ } satisfies DerivedEvents
174
+ })
175
+
176
+ const causeMessage = (cause: unknown): string => {
177
+ if (cause instanceof Error) return cause.message
178
+ return formatValue(cause)
179
+ }
180
+
181
+ const replayOf = (input: unknown, hasInput: boolean, events: ReadonlyArray<unknown>): CheckReplay =>
182
+ hasInput ? { input, events } : { events }
183
+
184
+ const planEvidence = (plan: {
185
+ readonly commands: ReadonlyArray<unknown>
186
+ readonly emittedEvents: ReadonlyArray<unknown>
187
+ readonly done: boolean
188
+ readonly output: unknown
189
+ }, state: unknown): string =>
190
+ formatValue({
191
+ state,
192
+ commands: plan.commands,
193
+ emitted: plan.emittedEvents,
194
+ done: plan.done,
195
+ output: plan.output
196
+ })
197
+
198
+ const statePaths = (step: { readonly afterConfiguration: ReadonlyArray<string> }): string =>
199
+ step.afterConfiguration.filter((path) => path !== "").join(", ")
200
+
201
+ export const check = <M extends AnyMachine>(
202
+ machine: ReadyMachine<M>,
203
+ options: CheckOptions<M> = {}
204
+ ): Effect.Effect<CheckReport, never, RunServices<M>> =>
205
+ Effect.gen(function*() {
206
+ const findings: Array<CheckFinding> = [...analyze(machine)]
207
+ const limits = new Set<CheckExplorationLimit>()
208
+ const seed = options.seed ?? 0
209
+ const hasInput = machine.input !== undefined && machine.input !== Schema.Void
210
+
211
+ let input: unknown = (options as { readonly input?: unknown }).input
212
+ if (hasInput && input === undefined) {
213
+ limits.add("sampledInput")
214
+ const sampled = yield* Effect.exit(Arbitrary.sampleEffect(Arbitrary.schema(machine.input), { count: 1, seed }))
215
+ if (Exit.isFailure(sampled)) {
216
+ findings.push({
217
+ law: "schema.underivable",
218
+ severity: "error",
219
+ message: `Could not derive machine input from its schema: ${
220
+ Cause.pretty(sampled.cause)
221
+ }. Pass input explicitly.`
222
+ })
223
+ return finish(machine, findings, limits, undefined)
224
+ }
225
+ input = sampled.value[0]
226
+ }
227
+
228
+ let events: ReadonlyArray<unknown>
229
+ if (options.events !== undefined) {
230
+ limits.add("customEvents")
231
+ events = options.events
232
+ } else {
233
+ const derived = yield* Effect.exit(deriveEvents(machine, seed, options.eventSamples ?? 3))
234
+ if (Exit.isFailure(derived)) {
235
+ findings.push({
236
+ law: "schema.underivable",
237
+ severity: "error",
238
+ message: `Could not derive events from their schemas: ${Cause.pretty(derived.cause)}. Pass events explicitly.`
239
+ })
240
+ return finish(machine, findings, limits, undefined)
241
+ }
242
+ if (!derived.value.enumerated) limits.add("sampledEvents")
243
+ events = derived.value.events
244
+ }
245
+ if (options.stateKey !== undefined) limits.add("customStateKey")
246
+ if (Machine.activityDefinitions(machine).length > 0) limits.add("invocations")
247
+
248
+ const replay = (replayEvents: ReadonlyArray<unknown>) => replayOf(input, hasInput, replayEvents)
249
+ const stateKey = options.stateKey ?? (({ snapshot }: { readonly snapshot: unknown }) => formatValue(snapshot))
250
+ const explored = yield* Effect.exit(
251
+ (explore as any)(machine, {
252
+ ...(hasInput ? { input } : {}),
253
+ limits: { ...defaultLimits, ...options.limits },
254
+ invariants: options.invariants,
255
+ stateKey,
256
+ // A completed machine accepts no further events.
257
+ events: ({ trace }: { readonly trace: Trace<M> }) =>
258
+ (trace.steps.at(-1)?.plan ?? trace.initial.plan).done ? [] : events
259
+ }) as Effect.Effect<any, RunFailure<unknown, M> | InvariantError<M>, RunServices<M>>
260
+ )
261
+
262
+ if (Exit.isFailure(explored)) {
263
+ const failure = Cause.findErrorOption(explored.cause)
264
+ if (failure._tag === "Some" && failure.value instanceof InvariantError) {
265
+ for (const violation of failure.value.violations) {
266
+ findings.push({
267
+ law: "invariant.violated",
268
+ severity: "error",
269
+ invariant: violation.invariant,
270
+ replay: replay(failure.value.trace.scenario.events),
271
+ message: `Invariant "${violation.invariant}" failed: ${violation.message}`
272
+ })
273
+ }
274
+ } else if (failure._tag === "Some") {
275
+ const runFailure = failure.value as RunFailure<unknown, M>
276
+ findings.push({
277
+ law: "planning.failed",
278
+ severity: "error",
279
+ replay: replay(runFailure.scenario.events),
280
+ message: `Planning failed: ${causeMessage(runFailure.cause)}`
281
+ })
282
+ } else {
283
+ if (Cause.hasInterruptsOnly(explored.cause)) return yield* Effect.interrupt
284
+ findings.push({
285
+ law: "planning.failed",
286
+ severity: "error",
287
+ replay: replay([]),
288
+ message: `A planning callback threw: ${Cause.pretty(explored.cause)}`
289
+ })
290
+ }
291
+ return finish(machine, findings, limits, undefined)
292
+ }
293
+
294
+ const exploration = explored.value
295
+ if (exploration.completeness._tag === "Truncated") {
296
+ for (const reason of exploration.completeness.reasons) limits.add(reason)
297
+ }
298
+
299
+ // Planning must be a function of the snapshot and the event. Plan each
300
+ // transition again and compare, because a syntax rule cannot see through a
301
+ // helper that reads the clock or randomness.
302
+ const initialTrace = (exploration.nodes[0] as ExplorationNode<M>).trace
303
+ const plannedAgain = yield* Effect.exit(
304
+ (hasInput
305
+ ? (Machine.planInitial as any)(machine, input)
306
+ : (Machine.planInitial as any)(machine)) as Effect.Effect<
307
+ InitialPlan<M>,
308
+ unknown,
309
+ RunServices<M>
310
+ >
311
+ )
312
+ if (
313
+ Exit.isSuccess(plannedAgain) &&
314
+ planEvidence(plannedAgain.value, plannedAgain.value.state) !==
315
+ planEvidence(initialTrace.initial.plan, initialTrace.initial.plan.state)
316
+ ) {
317
+ findings.push({
318
+ law: "planning.deterministic",
319
+ severity: "error",
320
+ source: "initial",
321
+ replay: replay([]),
322
+ message: "Startup planned differently from the same input. " +
323
+ "Do not read the clock, randomness, or external state in planning callbacks."
324
+ })
325
+ }
326
+
327
+ const seen = new Set<string>()
328
+ const graph = exploration.graph
329
+ for (
330
+ const edge of graph.edges.values() as Iterable<{ readonly source: number; readonly data: ExplorationEdge<M> }>
331
+ ) {
332
+ const source = graph.nodes.get(edge.source) as ExplorationNode<M>
333
+ const step: TraceStep<M> = edge.data.step
334
+ const location = `${statePaths({ afterConfiguration: step.beforeConfiguration })}:${
335
+ String((step.event as { readonly _tag: PropertyKey })._tag)
336
+ }`
337
+ const events = [...source.trace.scenario.events, step.event]
338
+
339
+ const verified = yield* Effect.exit(
340
+ verify(machine, {
341
+ ...source.trace,
342
+ scenario: { ...source.trace.scenario, events },
343
+ steps: [...source.trace.steps, step],
344
+ final: step.after,
345
+ finalConfiguration: step.afterConfiguration
346
+ })
347
+ )
348
+ if (Exit.isFailure(verified)) {
349
+ const failure = Cause.findErrorOption(verified.cause)
350
+ if (failure._tag === "Some" && failure.value instanceof VerificationError) {
351
+ for (const violation of failure.value.violations) {
352
+ findings.push({
353
+ law: "planning.verification",
354
+ severity: "error",
355
+ verificationLaw: violation.law,
356
+ replay: replay(events),
357
+ message: violation.message
358
+ })
359
+ }
360
+ }
361
+ }
362
+
363
+ const again = yield* Effect.exit(
364
+ ((Machine.plan as any)(machine, step.before, step.event)) as Effect.Effect<
365
+ EventPlan<M>,
366
+ unknown,
367
+ RunServices<M>
368
+ >
369
+ )
370
+ if (
371
+ Exit.isSuccess(again) &&
372
+ planEvidence(again.value, again.value.next) !== planEvidence(step.plan, step.after) &&
373
+ !seen.has(location)
374
+ ) {
375
+ seen.add(location)
376
+ findings.push({
377
+ law: "planning.deterministic",
378
+ severity: "error",
379
+ source: location,
380
+ replay: replay(events),
381
+ message: `Planning "${location}" produced a different result from the same snapshot and event. ` +
382
+ `Do not read the clock, randomness, or external state in planning callbacks.`
383
+ })
384
+ }
385
+ }
386
+
387
+ // Exploration does not run invocations, so it cannot take their outcomes or
388
+ // enter a state only they lead to. `limits` already reports that gap, and a
389
+ // warning for each such transition would only tell the reader to remove live code.
390
+ const visited = new Set<string>()
391
+ for (const node of exploration.nodes as ReadonlyArray<ExplorationNode<M>>) {
392
+ for (const path of node.configuration as ReadonlyArray<string>) visited.add(path)
393
+ }
394
+ const invocationsHideStates = limits.has("invocations")
395
+ for (const miss of exploration.transitionCoverage.branches.misses) {
396
+ if (miss.trigger.type === "invoke") continue
397
+ if (invocationsHideStates && !visited.has(miss.source)) continue
398
+ findings.push({
399
+ law: "transition.notCovered",
400
+ severity: "warning",
401
+ source: miss.source,
402
+ trigger: miss.trigger,
403
+ target: miss.branch.target,
404
+ ...(miss.branchKey === undefined ? {} : { branchKey: miss.branchKey }),
405
+ message:
406
+ `Exploration never took the ${
407
+ miss.trigger.type === "event" ? `"${String(miss.trigger.event)}"` : miss.trigger.type
408
+ } ` +
409
+ `transition from "${miss.source}"${miss.branch.target === undefined ? "" : ` to "${miss.branch.target}"`}. ` +
410
+ `Cover it with a scenario, or remove it if it cannot happen.`
411
+ })
412
+ }
413
+
414
+ return finish(machine, findings, limits, exploration)
415
+ })
416
+
417
+ const finish = (
418
+ machine: AnyMachine,
419
+ findings: ReadonlyArray<CheckFinding>,
420
+ limits: ReadonlySet<CheckExplorationLimit>,
421
+ exploration: {
422
+ readonly stats: { readonly states: number; readonly plannedTransitions: number }
423
+ readonly transitionCoverage: {
424
+ readonly definitions: { readonly total: number; readonly hit: number }
425
+ readonly branches: { readonly total: number; readonly hit: number }
426
+ }
427
+ } | undefined
428
+ ): CheckReport => ({
429
+ machine: machine.id ?? "Machine",
430
+ ok: findings.every((finding) => finding.severity !== "error"),
431
+ exploration: exploration !== undefined && limits.size === 0 ? "exhaustive" : "bounded",
432
+ limits: [...limits],
433
+ stats: exploration === undefined
434
+ ? { states: 0, plannedTransitions: 0, transitions: { total: 0, hit: 0 }, branches: { total: 0, hit: 0 } }
435
+ : {
436
+ states: exploration.stats.states,
437
+ plannedTransitions: exploration.stats.plannedTransitions,
438
+ transitions: {
439
+ total: exploration.transitionCoverage.definitions.total,
440
+ hit: exploration.transitionCoverage.definitions.hit
441
+ },
442
+ branches: {
443
+ total: exploration.transitionCoverage.branches.total,
444
+ hit: exploration.transitionCoverage.branches.hit
445
+ }
446
+ },
447
+ findings
448
+ })
449
+
450
+ const formatFinding = (finding: CheckFinding): string =>
451
+ ` ${finding.severity === "error" ? "error" : "warn "} ${finding.law}: ${finding.message}` +
452
+ ("replay" in finding ? `\n replay: ${formatValue(finding.replay)}` : "")
453
+
454
+ export const formatReport = (report: CheckReport): string =>
455
+ [
456
+ `${report.ok ? "PASS" : "FAIL"} ${report.machine}: ${report.stats.states} states, ` +
457
+ `${report.stats.branches.hit}/${report.stats.branches.total} branches, ${report.exploration}` +
458
+ (report.limits.length === 0 ? "" : ` (${report.limits.join(", ")})`),
459
+ ...report.findings.map(formatFinding)
460
+ ].join("\n")
@@ -86,11 +86,10 @@ const stateContext = <M extends AnyMachine>(machine: M, trace: Trace<M>): Explor
86
86
  const scenarioWithEvent = <M extends AnyMachine>(
87
87
  trace: Trace<M>,
88
88
  event: Machine.Machine.InputEvent<M>
89
- ): Scenario<M> =>
90
- ({
91
- ...trace.scenario,
92
- events: [...trace.scenario.events, event]
93
- }) as Scenario<M>
89
+ ): Scenario<M> => ({
90
+ ...trace.scenario,
91
+ events: [...trace.scenario.events, event]
92
+ })
94
93
 
95
94
  interface ExplorationEdgeDraft<M extends AnyMachine> {
96
95
  readonly source: number
@@ -96,7 +96,12 @@ export interface FiniteHistoryState {
96
96
  readonly fallback: string
97
97
  }
98
98
 
99
- /** A deterministic transient choice pseudo-state in a finite model. */
99
+ /**
100
+ * A deterministic transient choice pseudo-state in a finite model.
101
+ *
102
+ * @category models
103
+ * @since 0.47.0
104
+ */
100
105
  export interface FiniteChoiceState {
101
106
  readonly _tag: "Choice"
102
107
  readonly key: string
@@ -132,26 +137,17 @@ export type FiniteTransitionTrigger =
132
137
  | { readonly type: "done" }
133
138
 
134
139
  /**
135
- * One deterministic transition in a finite generated model.
140
+ * A public event transition may explicitly request source reentry.
136
141
  *
137
142
  * @category models
138
143
  * @since 0.4.0
139
144
  */
140
- interface FiniteTransitionBase {
145
+ export type FiniteEventTransition = {
141
146
  readonly source: string
142
147
  /** Omission represents a targetless transition. */
143
148
  readonly target?: string
144
149
  /** Optional schema-valid value supplied for the declared target state. */
145
150
  readonly targetValue?: number
146
- }
147
-
148
- /**
149
- * A public event transition may explicitly request source reentry.
150
- *
151
- * @category models
152
- * @since 0.4.0
153
- */
154
- export type FiniteEventTransition = FiniteTransitionBase & {
155
151
  readonly trigger: Extract<FiniteTransitionTrigger, { readonly type: "event" }>
156
152
  readonly reenter: boolean
157
153
  }
@@ -163,7 +159,12 @@ export type FiniteEventTransition = FiniteTransitionBase & {
163
159
  * @category models
164
160
  * @since 0.4.0
165
161
  */
166
- export type FiniteAutomaticTransition = FiniteTransitionBase & {
162
+ export type FiniteAutomaticTransition = {
163
+ readonly source: string
164
+ /** Omission represents a targetless transition. */
165
+ readonly target?: string
166
+ /** Optional schema-valid value supplied for the declared target state. */
167
+ readonly targetValue?: number
167
168
  readonly trigger: Exclude<FiniteTransitionTrigger, { readonly type: "event" }>
168
169
  }
169
170
 
@@ -597,6 +598,7 @@ const addGeneratedHistory = (
597
598
  event: leaveEvent,
598
599
  target: historyPath
599
600
  }),
601
+ // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- TypeScript 6 infers `readonly string[]` without it.
600
602
  events: Object.freeze([mutationEvent, leaveEvent, leaveEvent]) as readonly [string, string, string]
601
603
  })
602
604
  })
@@ -1266,7 +1268,7 @@ const construction = (
1266
1268
  [
1267
1269
  requestedChild ?? (sourcePath === path
1268
1270
  ? state.node.states.find((child) => child._tag !== "History" && child._tag !== "Choice")!.key
1269
- : sourcePath!.slice(path.length + 1).split(".")[0]!)
1271
+ : sourcePath.slice(path.length + 1).split(".")[0]!)
1270
1272
  ]
1271
1273
  : state.node.states.filter((child) => child._tag !== "History" && child._tag !== "Choice").map((child) =>
1272
1274
  child.key
@@ -1325,40 +1327,37 @@ const selectDefinitionTarget = (
1325
1327
  }
1326
1328
 
1327
1329
  const resolveDefinitionTarget = (
1328
- build: (config?: unknown) => unknown,
1330
+ select: any,
1329
1331
  source: string,
1330
1332
  target: string,
1331
1333
  byPath: ReadonlyMap<string, FlatFiniteState>,
1332
1334
  value?: number
1333
1335
  ): unknown => {
1334
1336
  const selected = byPath.get(target)!
1335
- if (selected.node._tag === "History") return build()
1337
+ if (selected.node._tag === "History") return select.history(target)
1336
1338
  const parts = target.split(".")
1337
1339
  const path = selected.root !== byPath.get(source)!.root
1338
1340
  ? parts[0]!
1339
1341
  : selectableDefinitionTarget(source, target, byPath)
1340
- return build(construction(path, byPath, parts, path.split(".").length - 1, source, value))
1342
+ return select.target(path, construction(path, byPath, parts, path.split(".").length - 1, source, value))
1341
1343
  }
1342
1344
 
1343
1345
  const makeHandlers = (
1344
1346
  states: ReadonlyArray<FiniteState>,
1345
1347
  parent: string | undefined,
1346
1348
  byPath: ReadonlyMap<string, FlatFiniteState>,
1347
- transitions: ReadonlyMap<string, FiniteTransition>,
1348
- branches: Record<string, Readonly<Record<string, unknown>>>
1349
+ transitions: ReadonlyMap<string, FiniteTransition>
1349
1350
  ): Record<string, unknown> => {
1350
1351
  const handlers: Record<string, unknown> = Object.create(null)
1351
1352
  for (const node of states) {
1352
1353
  const path = parent === undefined ? node.key : `${parent}.${node.key}`
1353
1354
  if (node._tag === "History") continue
1354
1355
  if (node._tag === "Choice") {
1355
- const group = `choice:${path}`
1356
- branches[group] = { destination: selectDefinitionTarget(path, node.selected, byPath) }
1357
1356
  handlers[node.key] = {
1358
1357
  choice: {
1359
- branches: group,
1358
+ branches: [selectDefinitionTarget(path, node.selected, byPath)],
1360
1359
  resolve: ({ select }: { readonly select: any }) =>
1361
- resolveDefinitionTarget(select.destination, path, node.selected, byPath)
1360
+ resolveDefinitionTarget(select, path, node.selected, byPath)
1362
1361
  }
1363
1362
  }
1364
1363
  continue
@@ -1372,19 +1371,18 @@ const makeHandlers = (
1372
1371
  let onDone: unknown
1373
1372
  for (const transition of transitions.values()) {
1374
1373
  if (transition.source !== path) continue
1375
- const group = `transition:${path}:${triggerKey(transition.trigger)}`
1376
- if (transition.target !== undefined) {
1377
- branches[group] = {
1378
- destination: selectDefinitionTarget(path, transition.target, byPath)
1379
- }
1380
- }
1374
+ const reenter = "reenter" in transition && transition.reenter === true
1381
1375
  const config = {
1382
- ...(transition.target === undefined ? { none: true } : {
1383
- branches: group,
1384
- resolve: ({ select }: { readonly select: any }) =>
1385
- resolveDefinitionTarget(select.destination, path, transition.target!, byPath, transition.targetValue)
1386
- }),
1387
- ...("reenter" in transition && transition.reenter ? { reenter: true } : {})
1376
+ ...(transition.target !== undefined ?
1377
+ {
1378
+ branches: [selectDefinitionTarget(path, transition.target, byPath)],
1379
+ resolve: ({ select }: { readonly select: any }) =>
1380
+ resolveDefinitionTarget(select, path, transition.target!, byPath, transition.targetValue)
1381
+ }
1382
+ : reenter ?
1383
+ {}
1384
+ : { stay: true }),
1385
+ ...(reenter ? { reenter: true } : {})
1388
1386
  }
1389
1387
  if (transition.trigger.type === "event") on[transition.trigger.event] = config
1390
1388
  else if (transition.trigger.type === "always") always = config
@@ -1433,7 +1431,7 @@ const makeHandlers = (
1433
1431
  .map((child) => [child.key, { decoded: true, data: stateValue(byPath.get(`${path}.${child.key}`)!) }])
1434
1432
  )
1435
1433
  }),
1436
- states: makeHandlers(node.states, path, byPath, transitions, branches)
1434
+ states: makeHandlers(node.states, path, byPath, transitions)
1437
1435
  }
1438
1436
  : {})
1439
1437
  }
@@ -1456,6 +1454,8 @@ export const compileModel = (model: FiniteModel): Machine.Machine.Any => {
1456
1454
  const flattened = validateModel(model)
1457
1455
  const byPath = new Map(flattened.map((state) => [state.path, state]))
1458
1456
  const stateTree = makeStateTree(model.roots, undefined)
1457
+ // Erased boundary: the public constructors infer literal state and event types,
1458
+ // but a finite model builds its schema tree and handlers at runtime.
1459
1459
  const defined = Machine.state({ states: stateTree } as any)
1460
1460
  const eventSchemas = model.events.map((event) => Schema.TaggedStruct(event, {}))
1461
1461
  const initial = byPath.get(model.initial)!
@@ -1463,13 +1463,11 @@ export const compileModel = (model: FiniteModel): Machine.Machine.Any => {
1463
1463
  `${transition.source}\u0000${triggerKey(transition.trigger)}`,
1464
1464
  transition
1465
1465
  ]))
1466
- const branches: Record<string, Readonly<Record<string, unknown>>> = Object.create(null)
1467
- const handlers = makeHandlers(model.roots, undefined, byPath, transitions, branches)
1466
+ const handlers = makeHandlers(model.roots, undefined, byPath, transitions)
1468
1467
  const machine = Machine.make({
1469
1468
  root: defined,
1470
- branches,
1471
- events: Machine.eventsFromSchemas(...eventSchemas) as any
1472
- } as any)
1469
+ events: Machine.eventsFromSchemas(...eventSchemas)
1470
+ })
1473
1471
  return machine.handle(
1474
1472
  {
1475
1473
  initial: {
@@ -1479,5 +1477,5 @@ export const compileModel = (model: FiniteModel): Machine.Machine.Any => {
1479
1477
  },
1480
1478
  states: handlers
1481
1479
  } as any
1482
- ) as Machine.Machine.Any
1480
+ )
1483
1481
  }