@typeonce/effect-machine 0.46.0 → 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} +234 -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} +42 -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 +1195 -1474
  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 +25 -19
  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.d.ts.map +1 -1
  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 +1139 -2130
  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 +38 -44
  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 +2 -4
  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
package/CLAUDE.md ADDED
@@ -0,0 +1,1823 @@
1
+ # Effect Machine documentation
2
+
3
+ This documentation covers `@typeonce/effect-machine` and its related packages.
4
+ It is generated for the installed version, so prefer it over any other copy.
5
+
6
+ **Note**: The examples contain comments for illustration. In practice, you would
7
+ not include them in your code.
8
+
9
+ ## Effect Machine agent guide
10
+
11
+ Use this guide to model a statechart with `@typeonce/effect-machine`. It covers
12
+ the decisions that shape the machine. Use the API reference for method
13
+ signatures, history states, and choice states.
14
+
15
+ Read [Effect Atom and React](#effect-atom-and-react) when React needs to consume
16
+ a machine. Keep React ownership and atom lookup out of the machine model.
17
+
18
+ ### Create a machine
19
+
20
+ Define schemas first, then states, events, the machine definition, and its
21
+ handlers. Export the state descriptor, public event descriptor, and implemented
22
+ machine. Tests, runtimes, and adapters can then use the same model.
23
+
24
+ ```ts
25
+ import { Machine } from "@typeonce/effect-machine"
26
+ import { Schema } from "effect"
27
+
28
+ const CounterState = Schema.TaggedUnion({
29
+ Running: { count: Schema.Number }
30
+ })
31
+
32
+ export const CounterStates = Machine.state({
33
+ states: {
34
+ Idle: {},
35
+ Running: CounterState.cases.Running
36
+ }
37
+ })
38
+
39
+ export const CounterEvents = Machine.eventsFromSchemas(
40
+ Schema.TaggedUnion({
41
+ Start: {},
42
+ Increment: {},
43
+ Stop: {}
44
+ })
45
+ )
46
+
47
+ export const CounterMachine = Machine.make({
48
+ id: "Counter",
49
+ root: CounterStates,
50
+ events: CounterEvents
51
+ }).handle({
52
+ initial: { target: "Idle" },
53
+ states: {
54
+ Idle: {
55
+ on: {
56
+ Start: { target: "Running", data: () => ({ count: 0 }) }
57
+ }
58
+ },
59
+ Running: {
60
+ on: {
61
+ Increment: { update: { Running: ({ state }) => ({ count: state.count + 1 }) } },
62
+ Stop: { target: "Idle" }
63
+ }
64
+ }
65
+ }
66
+ })
67
+ ```
68
+
69
+ Each step has one job:
70
+
71
+ - `Machine.state` declares the root, its child topology, and state-owned data.
72
+ - `Machine.events` declares the public messages the machine accepts and returns
73
+ typed event constructors.
74
+ - `Machine.make` joins the state tree, event protocol, input, and reusable sources.
75
+ - `.handle` declares initial children and implements the behavior of every active state and returns the
76
+ machine to export.
77
+
78
+ Chain `.handle` from `Machine.make`. Do not store the intermediate definition
79
+ when the module exports one machine implementation.
80
+
81
+ Use `data` for schema make input. Constructor defaults and validation run while
82
+ planning. Use `{ decoded: true, data }` for an existing schema Type; validation
83
+ still applies. `select.target` takes the same object format, with nested
84
+ children under `states`. Structural states omit data. See [Root machine API](#root-machine-api) for
85
+ startup input, root initialization, subtree construction, and history fallbacks.
86
+
87
+ The examples below show one modeling decision at a time. They omit unchanged
88
+ state and event declarations already shown above.
89
+
90
+ Start the implemented machine at the application boundary and send events
91
+ through the exported descriptor:
92
+
93
+ ```ts
94
+ import { Effect } from "effect"
95
+
96
+ const program = Effect.scoped(Effect.gen(function*() {
97
+ const counter = yield* Machine.start(CounterMachine)
98
+
99
+ yield* counter.send(CounterEvents.Start())
100
+ yield* counter.send(CounterEvents.Increment())
101
+ }))
102
+ ```
103
+
104
+ `Machine.start` requires a `Scope`. Closing it stops the machine and everything
105
+ it owns; use `ref.stop` to stop earlier.
106
+
107
+ ### Make impossible states unrepresentable
108
+
109
+ A finite state describes how the machine behaves now. State data holds values
110
+ needed while that mode is active.
111
+
112
+ Do not model mutually exclusive modes with separate flags such as `loading`,
113
+ `data`, and `error`. Those fields permit combinations such as loading with both
114
+ data and an error. Put the modes in the state tree instead:
115
+
116
+ ```ts
117
+ const RequestState = Schema.TaggedUnion({
118
+ Ready: { value: Schema.String },
119
+ Failed: { message: Schema.String }
120
+ })
121
+
122
+ const RequestStates = Machine.state({
123
+ states: {
124
+ Idle: {},
125
+ Loading: {},
126
+ Ready: RequestState.cases.Ready,
127
+ Failed: RequestState.cases.Failed
128
+ }
129
+ })
130
+ ```
131
+
132
+ The machine can now be `Loading`, `Ready`, or `Failed`. It cannot construct a
133
+ snapshot that represents two of those modes at once.
134
+
135
+ Use this test when deciding between a state and a field: if the value changes
136
+ which events the machine should handle, which work runs, or how the machine
137
+ behaves, model it as a state. Otherwise, keep it as data on the state that owns
138
+ it.
139
+
140
+ ### Put data on the lowest state that owns it
141
+
142
+ State data should exist only while it is valid. Put it on the lowest node whose
143
+ active subtree needs it. If several sibling states need the same data, their
144
+ compound parent owns it.
145
+
146
+ ```ts
147
+ const DocumentState = Schema.TaggedUnion({
148
+ Open: {
149
+ documentId: Schema.String,
150
+ draft: Schema.String
151
+ },
152
+ SaveFailed: {
153
+ message: Schema.String
154
+ }
155
+ })
156
+
157
+ const DocumentStates = Machine.state({
158
+ states: {
159
+ Closed: {},
160
+ Open: {
161
+ // Editing, Saving, and SaveFailed all need the document and draft.
162
+ schema: DocumentState.cases.Open,
163
+ states: {
164
+ Editing: {},
165
+ Saving: {},
166
+ // Only this state owns an error message.
167
+ SaveFailed: DocumentState.cases.SaveFailed
168
+ }
169
+ }
170
+ }
171
+ })
172
+ ```
173
+
174
+ Do not copy `documentId` and `draft` into every child. Copies can disagree after
175
+ a transition. Do not move `message` to `Open` either. That would allow an error
176
+ message while `Editing` or `Saving` is active.
177
+
178
+ ### Put shared behavior on the lowest common ancestor
179
+
180
+ Hierarchy owns behavior as well as data. Define a transition on the lowest
181
+ compound state whose children share it.
182
+
183
+ ```ts
184
+ const DocumentEvents = Machine.eventsFromSchemas(
185
+ Schema.TaggedUnion({
186
+ Close: {}
187
+ })
188
+ )
189
+
190
+ const DocumentMachine = Machine.make({
191
+ root: DocumentStates,
192
+ events: DocumentEvents
193
+ }).handle({
194
+ initial: { target: "Closed" },
195
+ states: {
196
+ Closed: {},
197
+ Open: {
198
+ initial: { target: "Open.Editing" },
199
+ on: {
200
+ // All Open children close the document in the same way.
201
+ Close: { target: "Closed" }
202
+ },
203
+ states: {
204
+ Editing: {},
205
+ Saving: {},
206
+ SaveFailed: {}
207
+ }
208
+ }
209
+ }
210
+ })
211
+ ```
212
+
213
+ The machine checks the deepest active state first, then its ancestors. Put a
214
+ handler on a child when that state needs different behavior. Keep the shared
215
+ case on the parent instead of repeating it in every child.
216
+
217
+ ### Treat events as the domain protocol
218
+
219
+ An event tells the machine what was requested or what happened. Name events
220
+ after domain actions and outcomes. Do not expose state setters such as
221
+ `SetLoading` or `SetError`.
222
+
223
+ ```ts
224
+ export const CheckoutEvents = Machine.eventsFromSchemas(
225
+ Schema.TaggedUnion({
226
+ Submit: {},
227
+ Cancel: {}
228
+ })
229
+ )
230
+
231
+ const CheckoutMachine = Machine.make({
232
+ root: CheckoutStates,
233
+ events: CheckoutEvents
234
+ }).handle({
235
+ states: {
236
+ Editing: {
237
+ on: {
238
+ Submit: { target: "Submitting" }
239
+ }
240
+ },
241
+ Submitting: {
242
+ on: {
243
+ // Cancel has meaning while work is in progress.
244
+ Cancel: { target: "Editing" }
245
+ }
246
+ },
247
+ Complete: {}
248
+ }
249
+ })
250
+ ```
251
+
252
+ The sender requests `Submit`. The machine decides whether `Submit` has a
253
+ transition in the current state. The sender does not choose `Submitting`.
254
+
255
+ Carry facts that the machine cannot read from its current snapshot in the event
256
+ payload. Do not copy current state into an event to help a handler reconstruct
257
+ what the machine already knows.
258
+
259
+ ### Use parallel states only for independent modes
260
+
261
+ A compound state activates one direct child. A parallel state activates one
262
+ child in every region. A parallel model therefore accepts the full product of
263
+ those regions.
264
+
265
+ ```ts
266
+ const ScreenStates = Machine.state({
267
+ states: {
268
+ Screen: {
269
+ type: "parallel",
270
+ states: {
271
+ connection: {
272
+ states: {
273
+ Online: {},
274
+ Offline: {}
275
+ }
276
+ },
277
+ panel: {
278
+ states: {
279
+ Closed: {},
280
+ Open: {}
281
+ }
282
+ }
283
+ }
284
+ }
285
+ }
286
+ })
287
+ const ScreenMachine = Machine.make({ root: ScreenStates, events: Machine.events({}) }).handle({
288
+ initial: { target: "Screen" },
289
+ states: {
290
+ Screen: {
291
+ states: {
292
+ connection: { initial: { target: "Screen.connection.Online" } },
293
+ panel: { initial: { target: "Screen.panel.Closed" } }
294
+ }
295
+ }
296
+ }
297
+ })
298
+ ```
299
+
300
+ This model permits all four combinations: online with a closed panel, online
301
+ with an open panel, offline with a closed panel, and offline with an open panel.
302
+
303
+ If one combination would break a domain rule, do not repair it with a UI check
304
+ or repeated cross-region conditions. Change the topology. A compound hierarchy
305
+ can place a mode only under the parent where it is valid.
306
+
307
+ ### Let states own running work
308
+
309
+ Put asynchronous work on the state whose meaning requires that work. The
310
+ machine starts the work when it enters the state and interrupts it when it exits.
311
+ Handle expected success and failure as transitions.
312
+
313
+ ```ts
314
+ const LoadState = Schema.TaggedUnion({
315
+ Loading: { documentId: Schema.String },
316
+ Ready: { content: Schema.String },
317
+ Failed: { message: Schema.String }
318
+ })
319
+
320
+ const LoadStates = Machine.state({
321
+ states: {
322
+ Idle: {},
323
+ Loading: LoadState.cases.Loading,
324
+ Ready: LoadState.cases.Ready,
325
+ Failed: LoadState.cases.Failed
326
+ }
327
+ })
328
+
329
+ const LoadMachine = Machine.make({
330
+ root: LoadStates,
331
+ effects: { loadDocument },
332
+ events: Machine.eventsFromSchemas()
333
+ }).handle({
334
+ initial: { target: "Idle" },
335
+ states: {
336
+ Idle: {},
337
+ Loading: {
338
+ invoke: {
339
+ src: "loadDocument",
340
+ input: ({ state }) => state.documentId,
341
+ onDone: { target: "Ready", data: ({ output }) => ({ content: output }) },
342
+ onFailure: { target: "Failed", data: ({ error }) => ({ message: String(error) }) }
343
+ }
344
+ },
345
+ Ready: {},
346
+ Failed: {}
347
+ }
348
+ })
349
+ ```
350
+
351
+ `loadDocument` may require Effect services. Those requirements remain on the
352
+ implemented machine type, so the runtime must provide them when it starts the
353
+ machine.
354
+
355
+ Model a per-instance capability, such as a router or a callback owned by a UI
356
+ component, as such a service. Do not put functions in state data or startup
357
+ input: snapshots must remain encodable. A React owner provides the capability
358
+ through its own runtime, as described in
359
+ [Per-owner capabilities](#per-owner-capabilities).
360
+
361
+ Do not start a promise inside a transition callback. A transition has no
362
+ lifetime in which to own that work. A state does.
363
+
364
+ Invoked work starts while the event that entered its state is processed. It
365
+ runs in the sender's turn until it first suspends, and its outcome is handled
366
+ in a later turn, even when the work completes without suspending. A state that
367
+ invokes work is therefore always observed before its outcome leaves it. Put a
368
+ browser call that requires user activation, such as `window.open` or
369
+ `navigator.clipboard.writeText`, in the first step of the invoked Effect:
370
+
371
+ ```ts
372
+ effects: {
373
+ authenticate: Effect.gen(function*() {
374
+ // Runs inside the click that sent the event.
375
+ const popup = yield* Effect.sync(() => window.open("about:blank", "auth", "popup"))
376
+ return yield* signInWithPopup(popup)
377
+ })
378
+ }
379
+ ```
380
+
381
+ The sender also runs any synchronous work before that first suspension. Keep
382
+ expensive synchronous computation behind a suspension or in a separate state.
383
+
384
+ Give every invocation declared by one state a unique lifecycle ID. Give every
385
+ logic or child process that can be active at the same time a unique runtime
386
+ address as well:
387
+
388
+ ```ts
389
+ // Register timers: { loadTimeout: "10 seconds" } in make.
390
+ Loading: {
391
+ invoke: [
392
+ {
393
+ src: "loadDocument",
394
+ input: ({ state }) => state.documentId,
395
+ onDone: { target: "Ready", data: ({ output }) => ({ content: output }) },
396
+ onFailure: { target: "Failed", data: ({ error }) => ({ message: String(error) }) }
397
+ },
398
+ { src: "loadTimeout", onDone: { target: "Idle" } }
399
+ ]
400
+ }
401
+ ```
402
+
403
+ Invocation outcomes are routed by state path and lifecycle ID, and overlapping
404
+ children cannot own the same runtime address. If work is sequential, represent
405
+ the sequence with separate states and transition from the first outcome. Do
406
+ not depend on one child completing quickly enough for another declaration to
407
+ reuse its identity.
408
+
409
+ #### Choose state-owned or process-owned children
410
+
411
+ Register a descriptor in `make({ children: { worker: Worker } })` and use
412
+ `invoke: { src: "worker", ...outcomes }` when a child belongs to one state and
413
+ must stop when that state exits. Use a child family and `children.spawn(...)`
414
+ inside a registered Effect when runtime events determine ids or cardinality
415
+ and the children must survive owner state changes. The Effect receives the
416
+ `children` capability through its invocation `input` mapper.
417
+
418
+ The Effect owns the startup attempt. The machine process owns every child that
419
+ starts successfully. Leaving `Commissioning` does not stop those children.
420
+ Stop one with `children.stop(Worker(id))` inside an Effect or
421
+ `enqueue.stop(Worker(id))` inside a transition. A duplicate active id fails
422
+ instead of replacing the existing child, and a partially successful group is
423
+ not rolled back automatically.
424
+
425
+ ### Keep transition decisions synchronous
426
+
427
+ A transition should choose the next state from the current snapshot and event.
428
+ Use ordinary TypeScript conditions when one event has several valid outcomes.
429
+
430
+ ```ts
431
+ const ReviewEvents = Machine.eventsFromSchemas(
432
+ Schema.TaggedUnion({
433
+ Evaluate: { score: Schema.Number }
434
+ })
435
+ )
436
+
437
+ const ReviewMachine = Machine.make({
438
+ root: ReviewStates,
439
+ events: ReviewEvents
440
+ }).handle({
441
+ initial: { target: "Pending" },
442
+ states: {
443
+ Pending: {
444
+ on: {
445
+ Evaluate: {
446
+ branches: [{ target: "Accepted" }, { target: "Rejected" }],
447
+ resolve: ({ event, select }) =>
448
+ event.score >= 80
449
+ ? select.target("Accepted")
450
+ : select.target("Rejected")
451
+ }
452
+ }
453
+ },
454
+ Accepted: {},
455
+ Rejected: {}
456
+ }
457
+ })
458
+ ```
459
+
460
+ Given the same snapshot and event, the handler should choose the same result.
461
+ Do not read the clock, generate randomness, call a service, or await work while
462
+ choosing a transition. Receive such values in an event or produce them through
463
+ state-owned work first.
464
+
465
+ `resolve` is checked against `branches` in both directions, and each `select`
466
+ call takes the values of the path it is given. An agent can edit this one
467
+ transition without reading anything else: a missing entry, an entry that is never
468
+ selected, and a path that returns nothing are all compile errors that name the fix.
469
+
470
+ A `{ stay: true }` accepts its event without changing state, so `Machine.can`
471
+ reports `true` when a resolver selects it. When the event must be refused, for
472
+ example to disable a control, use `guard`, or list `{ decline: true }` and return
473
+ `select.decline()` from the resolver. `guard` and `decline` exist only on `on`
474
+ handlers and `always`: an invocation outcome, a completion, and a choice have no
475
+ other candidate, so they use `{ stay: true }` or select a destination. A declined
476
+ invocation outcome would strand the machine in its state.
477
+
478
+ A `{ stay: true }` in one parallel region accepts the event, so it blocks a handler
479
+ for that event on a parallel ancestor. `{ decline: true }` lets that handler run.
480
+
481
+ Enqueue work with `commands` on any plain transition, and with `enqueue` in
482
+ `resolve`:
483
+
484
+ ```ts
485
+ Cancelled: {
486
+ target: "Archived",
487
+ commands: (_, enqueue) => enqueue.emit(Emitted.Cancelled())
488
+ }
489
+ ```
490
+
491
+ When only an active state's value changes, use `update` to preserve its active
492
+ descendants and running work:
493
+
494
+ ```ts
495
+ Changed: {
496
+ update: {
497
+ Document: ({ ancestors }) => ({
498
+ ...ancestors.Document,
499
+ revision: ancestors.Document.revision + 1
500
+ })
501
+ }
502
+ }
503
+ ```
504
+
505
+ Choose a valued source or retained ancestor explicitly. To change a parallel
506
+ sibling, send an event handled by that sibling. Combine a destination and one
507
+ retained owner update with `{ target, data, update: { Owner: ... } }`, where `data`
508
+ only ever means the target's value. Both values are validated atomically, and
509
+ destination entry sees the new owner value. A `branches` entry names the same pair
510
+ as `{ target, update: "Owner" }`, and its call passes the value:
511
+ `select.target(target, { data, update: { Owner: value } })`.
512
+
513
+ The destination of `{ target, update, data }` can be a choice. The owner is
514
+ updated before the choice resolves, so its resolver reads the new value through
515
+ `containingState`, `ancestors`, or `root`, and `data` returns only the complete
516
+ owner input. Every branch the choice can reach, including through nested
517
+ choices, must stay below the owner; otherwise the definition does not compile
518
+ and `handle` throws while naming the choice, branch, and escaping target.
519
+
520
+ ### Verify a machine after changing it
521
+
522
+ Run this after writing or changing a machine, before writing a specific test:
523
+
524
+ ```ts
525
+ import { MachineTest } from "@typeonce/effect-machine/testing"
526
+ import { Effect } from "effect"
527
+
528
+ const verifyCounter = Effect.gen(function*() {
529
+ const report = yield* MachineTest.check(CounterMachine)
530
+ if (!report.ok) yield* Effect.die(MachineTest.formatCheckReport(report))
531
+ })
532
+ ```
533
+
534
+ From a shell, `effect-machine check src/counter.ts --json` from
535
+ `@typeonce/effect-machine-devtools` does the same for every machine a file exports.
536
+
537
+ To fix a finding, keep the failing evidence first. Replay its events to reproduce
538
+ it, make the smallest behavior change, then run the check again. Do not silence a
539
+ finding by weakening a type or a test.
540
+
541
+ | Law | Meaning | Fix |
542
+ | ---------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------- |
543
+ | `topology.noPathFromInitial` | No declared transition can enter the state. | Add the missing transition, or remove the state. |
544
+ | `events.noHandler` | No state handles a public event. | Handle it, or remove it from the protocol. |
545
+ | `planning.deterministic` | The same snapshot and event planned two different results. | Move the clock, randomness, or external read into an event or work. |
546
+ | `planning.failed` | A planning callback threw or a value failed its schema. | Replay the events, then fix the callback or the value. |
547
+ | `planning.verification` | A planner law failed. This usually means an Effect Machine bug. | Report it with the replay. |
548
+ | `invariant.violated` | An invariant you supplied failed. | Replay the events, then fix the behavior or the invariant. |
549
+ | `transition.notCovered` | Exploration never took a declared branch. This is a warning. | Cover it with a scenario, or remove it if it cannot happen. |
550
+ | `schema.underivable` | Input or events could not be sampled from their schemas. | Pass `input` or `events` explicitly. |
551
+
552
+ A report is `"exhaustive"` only when `limits` is empty. Otherwise a pass means
553
+ nothing was found in what was explored. Keep sampled checks, bounded exploration,
554
+ and proof distinct when reporting a result. Invocations do not run during planning,
555
+ so test them on a started machine with `MachineTest.probe`.
556
+
557
+ ### Test paths and invariants
558
+
559
+ Test the statechart as a graph. Send domain events, inspect reached states, and
560
+ state the rules that every trace must preserve. Do not duplicate the handler's
561
+ branches inside the test.
562
+
563
+ ```ts
564
+ import { MachineTest } from "@typeonce/effect-machine/testing"
565
+ import { Effect, Option } from "effect"
566
+
567
+ const testProgram = Effect.gen(function*() {
568
+ const define = MachineTest.invariants(CounterMachine)
569
+
570
+ const countNeverBecomesNegative = define.state(
571
+ "count never becomes negative",
572
+ ({ snapshot }) =>
573
+ !CounterStates.matches(snapshot, "Running") ||
574
+ CounterStates.get(snapshot, "Running").pipe(
575
+ Option.exists(({ count }) => count >= 0)
576
+ ) ||
577
+ "count became negative"
578
+ )
579
+
580
+ const trace = yield* MachineTest.run(CounterMachine, {
581
+ events: [
582
+ CounterEvents.Start(),
583
+ CounterEvents.Increment(),
584
+ CounterEvents.Increment()
585
+ ]
586
+ })
587
+
588
+ yield* MachineTest.verify(CounterMachine, trace)
589
+ yield* MachineTest.checkInvariants(CounterMachine, trace, [
590
+ countNeverBecomesNegative
591
+ ])
592
+ })
593
+ ```
594
+
595
+ Use pure planner traces for state and transition rules. Start a live machine
596
+ and use `MachineTest.probe` when a test depends on timers, invoked work, raised
597
+ events, or runtime scheduling.
598
+
599
+ ### Choose observation deliberately
600
+
601
+ Use atom selectors to render state, invocation outcomes to express workflow
602
+ behavior, `ref.join` to await final output, and `ref.changes` for ongoing
603
+ observation. Emissions are non-replayed notifications; do not use them for work
604
+ the workflow depends on, such as navigation. Reach for
605
+ `Machine.waitFor(ref, predicate)` only when an external Effect or test must wait
606
+ for a specific current or subsequent snapshot, such as a long-lived connection
607
+ becoming ready. Compose `Effect.timeout` when needed.
608
+
609
+ Do not use `send` followed by `waitFor` as an acknowledgement protocol. The current
610
+ snapshot might already match, and a match does not identify which event caused
611
+ it. Keep workflow steps in the machine. A matching terminal snapshot succeeds;
612
+ an unmatched error preserves its Cause, stopping fails with `StoppedError`, and
613
+ completion without a match fails with `Cause.NoSuchElementError`.
614
+
615
+ Invoked Effects, Streams, and timers already receive a `Machine.invoke` Effect
616
+ span with machine, state, source, and invocation identity. Use ordinary Effect
617
+ tracing configuration and application spans such as `Effect.fn("Payments.charge")`.
618
+ Do not add manual spans around every transition or introduce a second exporter.
619
+ Sender trace context is not automatically carried through machine mailboxes.
620
+
621
+ #### Creating and running a machine
622
+
623
+ Declare the topology, the protocol, and the behavior, then start the result
624
+ inside a Scope.
625
+
626
+ ```ts
627
+ import { Machine } from "@typeonce/effect-machine"
628
+ import { Effect, Schema } from "effect"
629
+
630
+ // The root declares the topology and the data each state owns.
631
+ export const CounterStates = Machine.state({
632
+ states: {
633
+ Idle: {},
634
+ Running: { fields: { count: Schema.Number } }
635
+ }
636
+ })
637
+
638
+ // Events are the public protocol. Each one also becomes a typed constructor.
639
+ export const CounterEvents = Machine.events({ Start: {}, Increment: {}, Stop: {} })
640
+
641
+ // `make` joins the topology and protocol. `handle` implements every state and
642
+ // returns the machine to export.
643
+ export const CounterMachine = Machine.make({
644
+ id: "Counter",
645
+ root: CounterStates,
646
+ events: CounterEvents
647
+ }).handle({
648
+ initial: { target: "Idle" },
649
+ states: {
650
+ Idle: {
651
+ on: {
652
+ Start: { target: "Running", data: () => ({ count: 0 }) }
653
+ }
654
+ },
655
+ Running: {
656
+ on: {
657
+ Increment: { update: { Running: ({ state }) => ({ count: state.count + 1 }) } },
658
+ Stop: { target: "Idle" }
659
+ }
660
+ }
661
+ }
662
+ })
663
+
664
+ // `Machine.start` requires a Scope. Closing it stops the machine and everything
665
+ // the machine owns.
666
+ export const program = Effect.scoped(Effect.gen(function*() {
667
+ const counter = yield* Machine.start(CounterMachine)
668
+
669
+ yield* counter.send(CounterEvents.Start())
670
+ yield* counter.send(CounterEvents.Increment())
671
+ }))
672
+ ```
673
+
674
+ #### Choosing a destination from an event
675
+
676
+ List every destination in `branches`, next to the `resolve` that selects one.
677
+ The compiler checks one against the other, so this transition can be edited
678
+ without reading anything else.
679
+
680
+ ```ts
681
+ import { Machine } from "@typeonce/effect-machine"
682
+ import { Schema } from "effect"
683
+
684
+ export const CheckoutStates = Machine.state({
685
+ fields: { attempts: Schema.Number },
686
+ states: {
687
+ Editing: {},
688
+ Charging: { fields: { amount: Schema.Number } },
689
+ Paid: {}
690
+ }
691
+ })
692
+
693
+ export const CheckoutEvents = Machine.events({
694
+ Pay: { amount: Schema.Number },
695
+ Paid: {}
696
+ })
697
+
698
+ export const CheckoutMachine = Machine.make({
699
+ root: CheckoutStates,
700
+ events: CheckoutEvents
701
+ }).handle({
702
+ root: { attempts: 0 },
703
+ initial: { target: "Editing" },
704
+ states: {
705
+ Editing: {
706
+ on: {
707
+ Pay: {
708
+ // `stay` accepts the event, so `Machine.can` is true. `decline` refuses it, so `Machine.can` is false and a
709
+ // parent handler for the same event runs.
710
+ branches: [{ target: "Charging" }, { target: "Paid" }, { update: "root" }, { stay: true }, { decline: true }],
711
+ resolve: ({ event, root, select }) => {
712
+ if (event.amount < 0) return select.decline()
713
+ if (event.amount === 0) return select.target("Paid")
714
+ if (root.attempts >= 3) return select.stay()
715
+ if (event.amount > 1_000) return select.update({ root: { attempts: root.attempts + 1 } })
716
+ // Each call takes the values of the path it is given.
717
+ return select.target("Charging", { data: { amount: event.amount } })
718
+ }
719
+ }
720
+ }
721
+ },
722
+ Charging: {
723
+ on: {
724
+ Paid: { target: "Paid" }
725
+ }
726
+ }
727
+ }
728
+ })
729
+ ```
730
+
731
+ #### Updating retained state and enqueueing commands
732
+
733
+ `data` only ever means the target's value. `update` is a record naming the one
734
+ retained state it replaces. `commands` enqueues work on any plain transition.
735
+
736
+ ```ts
737
+ import { Machine } from "@typeonce/effect-machine"
738
+ import { Schema } from "effect"
739
+
740
+ export const DocumentEmitted = Machine.emittedEvents({ Saved: { revision: Schema.Number } })
741
+
742
+ export const DocumentMachine = Machine.make({
743
+ root: Machine.state({
744
+ states: {
745
+ Document: {
746
+ fields: { revision: Schema.Number },
747
+ states: {
748
+ Editing: {},
749
+ Saving: { fields: { draft: Schema.String } }
750
+ }
751
+ }
752
+ }
753
+ }),
754
+ events: Machine.events({ Change: {}, Save: { draft: Schema.String }, Saved: {} }),
755
+ emittedEvents: DocumentEmitted
756
+ }).handle({
757
+ initial: { target: "Document", data: { revision: 0 } },
758
+ states: {
759
+ Document: {
760
+ initial: { target: "Document.Editing" },
761
+ on: {
762
+ // Replaces the value of Document and keeps its active child and running work.
763
+ Change: { update: { Document: ({ state }) => ({ revision: state.revision + 1 }) } }
764
+ },
765
+ states: {
766
+ Editing: {
767
+ on: {
768
+ // Enters a state and replaces a retained ancestor in one validated step.
769
+ Save: {
770
+ target: "Document.Saving",
771
+ data: ({ event }) => ({ draft: event.draft }),
772
+ update: { Document: ({ ancestors }) => ({ revision: ancestors.Document.revision + 1 }) }
773
+ }
774
+ }
775
+ },
776
+ Saving: {
777
+ on: {
778
+ Saved: {
779
+ target: "Document.Editing",
780
+ commands: ({ ancestors }, enqueue) =>
781
+ enqueue.emit(DocumentEmitted.Saved({ revision: ancestors.Document.revision }))
782
+ }
783
+ }
784
+ }
785
+ }
786
+ }
787
+ }
788
+ })
789
+ ```
790
+
791
+ #### Verifying a machine after changing it
792
+
793
+ Run `MachineTest.check` after every change. It needs no test setup, and a
794
+ finding names the law it broke and the events that reproduce it.
795
+
796
+ ```ts
797
+ import { Machine } from "@typeonce/effect-machine"
798
+ import { MachineTest } from "@typeonce/effect-machine/testing"
799
+ import { Effect } from "effect"
800
+
801
+ export const SwitchMachine = Machine.make({
802
+ root: Machine.state({ states: { Off: {}, On: {} } }),
803
+ events: Machine.events({ Toggle: {} })
804
+ }).handle({
805
+ initial: { target: "Off" },
806
+ states: {
807
+ Off: { on: { Toggle: { target: "On" } } },
808
+ On: { on: { Toggle: { target: "Off" } } }
809
+ }
810
+ })
811
+
812
+ export const verified = Effect.gen(function*() {
813
+ const report = yield* MachineTest.check(SwitchMachine)
814
+ if (!report.ok) {
815
+ return yield* Effect.die(MachineTest.formatCheckReport(report))
816
+ }
817
+ // "exhaustive" means nothing limited exploration. "bounded" lists why in `limits`, and is not a proof.
818
+ return report.exploration
819
+ })
820
+ ```
821
+
822
+ ## Root machine API
823
+
824
+ A machine has one root state. It can own data, child topology, both, or neither.
825
+ `Machine.state` declares that structure; `Machine.make` declares protocols and
826
+ reusable sources; `.handle` supplies initialization and behavior.
827
+
828
+ ### Startup input and state data
829
+
830
+ ```ts
831
+ import { Machine } from "@typeonce/effect-machine"
832
+ import { Schema } from "effect"
833
+
834
+ const Root = Machine.state({
835
+ fields: { locale: Schema.String },
836
+ states: {
837
+ Loading: { fields: { documentId: Schema.String } },
838
+ Ready: {}
839
+ }
840
+ })
841
+ const Events = Machine.events({
842
+ Loaded: {},
843
+ Reload: { locale: Schema.String, documentId: Schema.String }
844
+ })
845
+ const Document = Machine.make({
846
+ root: Root,
847
+ events: Events,
848
+ input: Schema.Struct({ locale: Schema.String, documentId: Schema.String })
849
+ }).handle({
850
+ root: ({ input }) => ({ locale: input.locale }),
851
+ initial: {
852
+ target: "Loading",
853
+ data: ({ input }) => ({ documentId: input.documentId })
854
+ },
855
+ on: {
856
+ Reload: {
857
+ initialize: ({ event }) => ({ locale: event.locale, documentId: event.documentId }),
858
+ reenter: true
859
+ }
860
+ },
861
+ states: {
862
+ Loading: { on: { Loaded: { target: "Ready" } } }
863
+ }
864
+ })
865
+ ```
866
+
867
+ Start with `Machine.start(Document, { locale: "en", documentId: "intro" })`.
868
+ Root construction runs before its initial child construction. Both receive the
869
+ same validated input. `documentId` belongs only to Loading; it need not be stored
870
+ in root data. Input is not retained as a reset value on the machine or snapshot.
871
+
872
+ Only the root's initial callbacks receive machine input. Nested initial callbacks
873
+ receive their owning state, ancestors, root, and lifecycle event. Pass any needed
874
+ values through the nested state's data. Input is not an entry/exit capability.
875
+
876
+ For a parallel root, every required region constructor receives input:
877
+
878
+ ```ts
879
+ initial: {
880
+ Documents: ({ input }) => ({ folder: input.folder }),
881
+ Connection: ({ input }) => ({ endpoint: input.endpoint })
882
+ }
883
+ ```
884
+
885
+ Structural regions require no data. Schema constructor defaults can supply
886
+ optional region data. Compound handlers declare one direct initial child with
887
+ `initial: { target, data }`; each compound has its own initial declaration.
888
+ There is no `initialConfiguration` or initializer in `make`.
889
+
890
+ ### Root initialization and updates
891
+
892
+ The root is spelled `"root"` in declarations, so a top-level state cannot use
893
+ that name. It is not a transition destination.
894
+
895
+ `{ initialize: ... }` reconstructs root data and follows its initial
896
+ declarations using fresh machine input: a value or a callback of the transition
897
+ context. A machine without input declares `{ initialize: true }`. `initialize`
898
+ rejects `target`, `update`, `history`, `stay`, `data`, and `decoded`. A `branches`
899
+ entry declares `{ initialize: true }`, and its resolver passes the input with
900
+ `select.initialize({ input })`.
901
+
902
+ Initializing root retains its lifecycle unless it is reentered. Put a machine-wide
903
+ reset handler at root and use `reenter: true` to exit and enter root as well as
904
+ its descendants. Reentry restarts work owned by the exited states. Without
905
+ reentry, retained root work continues; it does not automatically acquire new
906
+ construction values. Ordinary transition conflict and lifecycle rules still apply.
907
+ This does not create a new machine reference or discard history records.
908
+
909
+ `{ update: { root: ... } }` instead replaces root's complete value,
910
+ retaining its active children and running work. It takes no input and does not
911
+ run initial constructors. Other source/ancestor updates follow the same rules.
912
+
913
+ ### Inline and branching construction
914
+
915
+ Ordinary transitions stay inline:
916
+
917
+ ```ts
918
+ Load: {
919
+ target: "Loading",
920
+ data: ({ event }) => ({ documentId: event.documentId })
921
+ }
922
+ ```
923
+
924
+ Targeting a compound or parallel state follows its initial declarations. Event
925
+ transitions use `target`, never `initial`. `initial` names only handler startup
926
+ edges. `history` restores a declared history state; `stay: true` accepts an
927
+ event without changing its target configuration.
928
+
929
+ List `branches` next to `resolve` when a transition chooses an outcome or builds
930
+ an explicit subtree. The compiler checks one against the other in both directions:
931
+
932
+ ```ts
933
+ Open: {
934
+ branches: [{ target: "Checkout" }, { stay: true }],
935
+ resolve: ({ event, select }) => event.open
936
+ ? select.target("Checkout", {
937
+ data: { cartId: event.cartId },
938
+ states: { Review: { data: { total: event.total } } }
939
+ })
940
+ : select.stay()
941
+ }
942
+ ```
943
+
944
+ Objects contain computed values, not nested constructor callbacks. `data` is
945
+ schema make input; `{ decoded: true, data: value }` supplies the decoded type.
946
+ Both paths validate and report typed schema failures before committing changes.
947
+ The decoded flag applies only to its own node. Structural nodes reject data.
948
+
949
+ Omitting `states` follows declared initial children. Explicit compound
950
+ construction selects exactly one child. Entering an inactive parallel subtree
951
+ requires every region. Source-local parallel construction can select a single
952
+ region while retaining its active siblings, preserving the existing scope rules.
953
+ Names under `states` cannot collide with construction metadata.
954
+
955
+ Each branch's destination remains inspectable without executing `resolve`.
956
+ Dynamically selected descendants are visible after resolution; this API does not
957
+ add static analysis of resolver bodies.
958
+
959
+ ### Retained-owner updates
960
+
961
+ An inline combined transition keeps the target's value and the owner's value
962
+ separate, so `data` only ever means the target's value:
963
+
964
+ ```ts
965
+ Save: {
966
+ target: "Checkout.Saving",
967
+ data: ({ event }) => ({ requestId: event.requestId }),
968
+ update: { Checkout: ({ event }) => ({ cartId: event.cartId }) }
969
+ }
970
+ ```
971
+
972
+ A `branches` entry names the same pair, `{ target: "Checkout.Saving", update: "Checkout" }`,
973
+ and its call constructs both:
974
+
975
+ ```ts
976
+ select.target("Checkout.Saving", {
977
+ data: { requestId: event.requestId },
978
+ update: { Checkout: { cartId: event.cartId } }
979
+ })
980
+ ```
981
+
982
+ `update` takes exactly one owner. It is not an
983
+ arbitrary nested-state operation. The owner must be active and retained across
984
+ the transition. Both complete values validate before either is committed.
985
+
986
+ ### History and lifecycle
987
+
988
+ History fallback uses a bound function with the same node object format:
989
+
990
+ ```ts
991
+ history: {
992
+ recent: {
993
+ default: ({ target }) => target({
994
+ states: {
995
+ Checkout: {
996
+ data: { cartId: "new" },
997
+ states: { Review: { data: { total: 0 } } }
998
+ }
999
+ }
1000
+ })
1001
+ }
1002
+ }
1003
+ ```
1004
+
1005
+ A fallback must explicitly construct a complete tree containing its owner,
1006
+ including required ancestors and parallel siblings. Its root data is state data,
1007
+ not startup input. `Machine.resume` restores a validated snapshot without rerunning
1008
+ startup constructors.
1009
+
1010
+ `guard` declines before construction. A resolver may return `select.decline()` only
1011
+ when `branches` lists `{ decline: true }`. Both exist only on `on` handlers and
1012
+ `always`. Effect, Stream, timer, logic, child invocation, completion,
1013
+ entry/exit, and required outcome channels retain their existing contracts.
1014
+
1015
+ ## Effect Atom and React
1016
+
1017
+ React code should own one stable machine atom, pass it through props or
1018
+ Context, and subscribe in the descendants that render machine state. Keep the
1019
+ machine definition free of React dependencies.
1020
+
1021
+ Read [Effect Machine agent guide](#effect-machine-agent-guide) for statechart
1022
+ modeling, transitions, services, and testing.
1023
+
1024
+ ### Recommended folder structure
1025
+
1026
+ ```text
1027
+ src/
1028
+ ├── context/
1029
+ │ └── auth-machine-context.tsx # React ownership and distribution
1030
+ ├── lib/
1031
+ │ ├── atom-runtime.ts # Shared bound AtomMachine runtime
1032
+ │ └── services/
1033
+ └── machines/
1034
+ └── auth-machine.ts # States, events, and behavior
1035
+ ```
1036
+
1037
+ `auth-machine.ts` owns the workflow. A Context module only creates and distributes
1038
+ the machine atom. State-slot components decide which state paths they render.
1039
+
1040
+ Bind service-backed machines once at the application runtime:
1041
+
1042
+ ```ts
1043
+ import { AtomMachine } from "@typeonce/effect-machine/reactivity"
1044
+ import { Atom } from "effect/reactivity"
1045
+ import { AppLayer } from "./app-layer"
1046
+
1047
+ const atomRuntime = Atom.runtime(AppLayer)
1048
+
1049
+ export const MachineAtoms = AtomMachine.bind(atomRuntime)
1050
+ ```
1051
+
1052
+ Service-free machines can use `AtomMachine.make` directly.
1053
+
1054
+ ### Own a machine in one React subtree
1055
+
1056
+ Create a context from a factory. Each Provider owns a fresh bridge in its current
1057
+ Atom registry; it does not subscribe to state changes.
1058
+
1059
+ ```tsx
1060
+ import { createMachineContext } from "@typeonce/effect-machine-react"
1061
+ import { MachineAtoms } from "../lib/atom-runtime"
1062
+ import { AuthMachine } from "../machines/auth-machine"
1063
+
1064
+ export const Auth = createMachineContext(({ input }: { input: AuthInput }) => MachineAtoms.make(AuthMachine, input))
1065
+ export const useAuthMachine = Auth.useMachine
1066
+
1067
+ function AuthRoute({ input, attemptId }: Props) {
1068
+ return (
1069
+ <Auth.Provider key={attemptId} input={input}>
1070
+ <AuthCard />
1071
+ </Auth.Provider>
1072
+ )
1073
+ }
1074
+ ```
1075
+
1076
+ The factory takes one options object, and each option it declares is a
1077
+ Provider prop of the same name and type. A machine without input can pass
1078
+ `MachineAtoms.factory(Machine)` directly, and its Provider takes no `input`.
1079
+ Input is startup-only. Send events to update the existing workflow; change the
1080
+ Provider's React key to create a new one. `MachineState` does not suspend, so
1081
+ the first paint needs no Suspense boundary. Custom readers that use
1082
+ `useAtomSuspense` still suspend during startup; keep the Provider above their
1083
+ Suspense boundary so suspension does not discard the owner. Supply an Atom
1084
+ RegistryProvider at the application boundary. The same factory used by two Providers creates isolated
1085
+ machines, even when their inputs are equal.
1086
+
1087
+ `useMachineAtom(() => makeMachine(input))` remains available for custom owners.
1088
+ It mounts the reference after commit without reading `result` or `snapshot`.
1089
+
1090
+ ### Per-owner capabilities
1091
+
1092
+ A router, a callback owned by a component, or another per-instance capability
1093
+ is a service, never a schema field or startup input. Declare the service, let a
1094
+ state invoke the work that needs it, and provide the implementation from the
1095
+ React owner:
1096
+
1097
+ ```tsx
1098
+ import { Machine } from "@typeonce/effect-machine"
1099
+ import { useMachineAtom } from "@typeonce/effect-machine-react"
1100
+ import { AtomMachine } from "@typeonce/effect-machine/reactivity"
1101
+ import { Context, Effect, Layer } from "effect"
1102
+ import { Atom } from "effect/reactivity"
1103
+ import { AppLayer } from "../lib/app-layer"
1104
+
1105
+ export class Navigation extends Context.Service<Navigation, {
1106
+ readonly push: (href: string) => Effect.Effect<void>
1107
+ }>()("Navigation") {}
1108
+
1109
+ export const OnboardingMachine = Machine.make({
1110
+ root: Machine.state({
1111
+ states: { Editing: {}, Leaving: {}, Done: { type: "final" } }
1112
+ }),
1113
+ events: Machine.events({ Submit: {} }),
1114
+ effects: {
1115
+ navigateNext: Effect.flatMap(Navigation, (navigation) => navigation.push("/onboarding/next"))
1116
+ }
1117
+ }).handle({
1118
+ initial: { target: "Editing" },
1119
+ states: {
1120
+ Editing: { on: { Submit: { target: "Leaving" } } },
1121
+ Leaving: { invoke: { src: "navigateNext", onDone: { target: "Done" } } },
1122
+ Done: {}
1123
+ }
1124
+ })
1125
+
1126
+ function OnboardingRoute() {
1127
+ const router = useRouter()
1128
+ const machine = useMachineAtom(() =>
1129
+ AtomMachine
1130
+ .bind(Atom.runtime(Layer.merge(
1131
+ AppLayer,
1132
+ Layer.succeed(Navigation, {
1133
+ push: (href) => Effect.sync(() => router.push(href))
1134
+ })
1135
+ )))
1136
+ .make(OnboardingMachine)
1137
+ )
1138
+
1139
+ return <OnboardingForm machine={machine} />
1140
+ }
1141
+ ```
1142
+
1143
+ The requirement stays on the machine type. Binding the machine to a runtime
1144
+ without `Navigation`, such as the application-wide `MachineAtoms`, is a compile
1145
+ error. Snapshots contain only schema data, so `Machine.encodeSnapshot` keeps
1146
+ working, and tests substitute the capability with `Layer.mock(Navigation, ...)`.
1147
+
1148
+ Create the runtime inside the `useMachineAtom` factory so each owner builds it
1149
+ once. `Atom.runtime` builds layers through the registry's memo map: the shared
1150
+ `AppLayer` is built once per registry and reused, and each owner builds only its
1151
+ own capability layer. Use `Layer.provideMerge(ownerLayer, AppLayer)` when the
1152
+ owner layer itself needs application services.
1153
+
1154
+ To share the owner-bound machine with a subtree, declare the capability as a
1155
+ `layer` option of a `createMachineContext` factory. `OnboardingMachine` has no
1156
+ input, so the factory declares only `layer`:
1157
+
1158
+ ```tsx
1159
+ import { createMachineContext } from "@typeonce/effect-machine-react"
1160
+
1161
+ const navigationLayer = (router: Router) =>
1162
+ Layer.succeed(Navigation, {
1163
+ push: (href) => Effect.sync(() => router.push(href))
1164
+ })
1165
+
1166
+ export const Onboarding = createMachineContext(
1167
+ ({ layer }: { layer: Layer.Layer<Navigation> }) =>
1168
+ AtomMachine
1169
+ .bind(Atom.runtime(Layer.provideMerge(layer, AppLayer)))
1170
+ .make(OnboardingMachine)
1171
+ )
1172
+
1173
+ function OnboardingRoute() {
1174
+ return (
1175
+ <Onboarding.Provider layer={navigationLayer(useRouter())}>
1176
+ <OnboardingForm />
1177
+ </Onboarding.Provider>
1178
+ )
1179
+ }
1180
+ ```
1181
+
1182
+ The Provider requires a `layer` prop of exactly the declared `Layer` type, and
1183
+ an `input` prop when the factory also declares input, as in
1184
+ `({ input, layer }: { input: SignInInput; layer: Layer.Layer<Navigation> })`.
1185
+ Options other than `input` and `layer` are rejected, so a capability cannot
1186
+ travel under another name. A factory without a `layer` option has a Provider
1187
+ without a `layer` prop. Like `input`, the layer is read once, when the Provider
1188
+ mounts: a new router instance does not rebuild the running machine. Change the
1189
+ Provider's React `key` to create a new owner with a new layer. Binding still
1190
+ checks the machine's requirements, so a layer type that omits `Navigation` is a
1191
+ compile error.
1192
+
1193
+ ### Render state-owned data
1194
+
1195
+ Render a typed path in the smallest component that needs it:
1196
+
1197
+ ```tsx
1198
+ import { MachineState } from "@typeonce/effect-machine-react"
1199
+
1200
+ function EditingFields() {
1201
+ const machine = useAuthMachine()
1202
+ return (
1203
+ <MachineState machine={machine} path="Editing" inactive={null}>
1204
+ {({ value }) => <EmailField email={value.email} />}
1205
+ </MachineState>
1206
+ )
1207
+ }
1208
+ ```
1209
+
1210
+ `MachineState` subscribes only its renderer. The path determines the callback's
1211
+ snapshot type. It does not suspend: until the machine has a snapshot it renders
1212
+ `pending`, and an inactive path renders `inactive` (both null by default).
1213
+ Startup and runtime failures reach the nearest error boundary. Once a snapshot
1214
+ has rendered, the renderer keeps it while the machine is still starting, for
1215
+ example while a bound runtime layer builds after hydration.
1216
+
1217
+ `MachineState` also renders a child machine. Pass the child bridge; paths and
1218
+ the snapshot are then the child's, and `inactive` also renders while the state
1219
+ that owns the child is not active:
1220
+
1221
+ ```tsx
1222
+ <MachineState machine={machine.child(QuantityChild)} path="" inactive={null}>
1223
+ {(snapshot) => <NumberField value={snapshot.value.quantity} />}
1224
+ </MachineState>
1225
+ ```
1226
+
1227
+ For custom hooks, `useMachineResult(atom)` reads any result atom, such as
1228
+ `AtomMachine.selectSnapshot(machine, path)`, `matches`, or `can`, with the same
1229
+ rendering semantics as `MachineState`: it does not suspend, serves the planned
1230
+ value during server rendering and hydration, and keeps the last `Success` while
1231
+ the machine is still starting. Prefer it to `useAtomValue`, which returns
1232
+ `Initial` again after hydration and makes the renderer replace hydrated markup.
1233
+ `useAtomSuspense(AtomMachine.selectSnapshot(machine, path)).value` returns an
1234
+ Option of the selected snapshot for readers inside a Suspense boundary.
1235
+
1236
+ `AtomMachine.select` returns the selected state value.
1237
+ `AtomMachine.selectSnapshot` also retains the selected state's child topology.
1238
+ Both return `Option.none()` while the path is inactive. Do not replace that
1239
+ absence with an empty string, `null`, or a global boolean.
1240
+
1241
+ Repeated calls with the same machine and path return the same atom, so path
1242
+ selection is safe during render without `useMemo`. Equal selected values do not
1243
+ notify the component.
1244
+
1245
+ Nested paths keep the same ownership:
1246
+
1247
+ ```tsx
1248
+ function PasswordField() {
1249
+ const machine = useAuthMachine()
1250
+ const password = useAtomSuspense(
1251
+ AtomMachine.select(machine, "Editing.Password")
1252
+ ).value
1253
+
1254
+ return Option.match(password, {
1255
+ onNone: () => null,
1256
+ onSome: ({ password }) => <input type="password" value={password} />
1257
+ })
1258
+ }
1259
+ ```
1260
+
1261
+ Place independent subscriptions in independent descendants:
1262
+
1263
+ ```tsx
1264
+ function AuthCard() {
1265
+ return (
1266
+ <>
1267
+ <EditingFields />
1268
+ <VerificationFields />
1269
+ <FailureMessage />
1270
+ <SubmitButton />
1271
+ </>
1272
+ )
1273
+ }
1274
+ ```
1275
+
1276
+ Atom granularity cannot isolate hooks that all live in `AuthCard`. Any selected
1277
+ change rerenders the component that called the hook.
1278
+
1279
+ ### Send without subscribing
1280
+
1281
+ Use the writable atom directly:
1282
+
1283
+ ```tsx
1284
+ import { useAtomSet } from "@effect/atom-react"
1285
+
1286
+ function SubmitButton() {
1287
+ const machine = useAuthMachine()
1288
+ const send = useAtomSet(machine.send)
1289
+
1290
+ return (
1291
+ <button onClick={() => send({ _tag: "Submitted" })}>
1292
+ Continue
1293
+ </button>
1294
+ )
1295
+ }
1296
+ ```
1297
+
1298
+ `useAtomSet` mounts the writable atom and does not subscribe the component to
1299
+ its value.
1300
+
1301
+ A write to a ready machine is processed inside the event handler, and work
1302
+ invoked by the entered state starts there too. A browser call that requires
1303
+ user activation, such as `window.open`, `navigator.clipboard.writeText`, or
1304
+ `HTMLMediaElement.play`, can therefore run in the first step of the invoked
1305
+ Effect. A write held while the machine is still starting is delivered later,
1306
+ outside the user's gesture.
1307
+
1308
+ Writes made while the machine is still starting, for example while a bound
1309
+ `Atom.runtime` layer is building after hydration, are held and delivered in
1310
+ write order once the machine is ready. The write result stays waiting until
1311
+ the event is delivered and fails with the startup error if startup fails.
1312
+ Writes after the machine stopped or completed fail with `StoppedError`. The
1313
+ same applies to `stop` and to child `send` and `stop`; a child command fails
1314
+ with `ChildNotActiveError` when the state that owns the child is not active.
1315
+
1316
+ ### Query concrete event acceptance
1317
+
1318
+ `AtomMachine.can` turns one concrete event input into a reusable machine
1319
+ projection. Declare the projection once, then apply it to the React-owned
1320
+ machine. Repeated applications to the same machine return the same atom:
1321
+
1322
+ ```tsx
1323
+ import { useAtomSet, useAtomSuspense } from "@effect/atom-react"
1324
+ import { AtomMachine } from "@typeonce/effect-machine/reactivity"
1325
+ import { AuthEvents } from "../machines/auth-machine"
1326
+
1327
+ const submitAllowed = AtomMachine.can(AuthEvents.Submitted())
1328
+
1329
+ function SubmitButton() {
1330
+ const machine = useAuthMachine()
1331
+ const canSubmit = useAtomSuspense(submitAllowed(machine)).value
1332
+ const send = useAtomSet(machine.send)
1333
+
1334
+ return (
1335
+ <button
1336
+ disabled={!canSubmit}
1337
+ onClick={() => send(AuthEvents.Submitted())}
1338
+ >
1339
+ Continue
1340
+ </button>
1341
+ )
1342
+ }
1343
+ ```
1344
+
1345
+ Startup still suspends, startup and runtime failures reach the error boundary,
1346
+ and invalid event input for an active machine remains a
1347
+ `MachineSchemaDecodeError`. Done and stopped machines return `false`.
1348
+
1349
+ When acceptance depends on a changing payload, project an event atom instead:
1350
+
1351
+ ```ts
1352
+ import { Atom } from "effect/reactivity"
1353
+
1354
+ const submitEvent = Atom.map(draftAtom, (draft) => AuthEvents.Submitted({ draft }))
1355
+
1356
+ const submitAllowed = AtomMachine.can(submitEvent)
1357
+ ```
1358
+
1359
+ Changes to `draftAtom` recompute acceptance. The event atom contains the event
1360
+ input itself rather than an `AsyncResult`.
1361
+
1362
+ `can` is `true` whenever the active configuration selects a transition. A
1363
+ `{ stay: true }` branch is a selected transition: it accepts the event without
1364
+ changing state. A resolver that falls back to `stay` therefore keeps the button
1365
+ enabled:
1366
+
1367
+ ```ts
1368
+ // Before: an incomplete form still accepts Submitted, so `can` is true.
1369
+ Submitted: {
1370
+ branches: [{ target: "Reviewing" }, { stay: true }],
1371
+ resolve: ({ state, select }) =>
1372
+ state.email.length > 0 ? select.target("Reviewing") : select.stay()
1373
+ }
1374
+ ```
1375
+
1376
+ When the event must be refused, decline it. Use `guard` for an ordinary
1377
+ transition, or `{ decline: true }` with `select.decline()` in a resolver:
1378
+
1379
+ ```ts
1380
+ // After: an incomplete form declines Submitted, so `can` is false.
1381
+ Submitted: { target: "Reviewing", guard: ({ state }) => state.email.length > 0 }
1382
+
1383
+ // A resolver that needs commands or construction declines explicitly.
1384
+ Submitted: {
1385
+ branches: [{ target: "Reviewing" }, { decline: true }],
1386
+ resolve: ({ state, select }) =>
1387
+ state.email.length > 0 ? select.target("Reviewing") : select.decline()
1388
+ }
1389
+ ```
1390
+
1391
+ Keep `stay` for events that are deliberately accepted and ignored. The
1392
+ `effect-machine/no-conditional-stay-branch` lint rule reports the conditional
1393
+ fallback.
1394
+
1395
+ Query acceptance during render through `AtomMachine.can(event)(machine)`. Do
1396
+ not call `Effect.runSync(Machine.can(...))` in a component: the atom shares the
1397
+ running machine's snapshot, suspends during startup, and recomputes when the
1398
+ snapshot changes.
1399
+
1400
+ ### Whole-result and custom selections
1401
+
1402
+ Reading the full result is correct when a component renders the complete
1403
+ machine state:
1404
+
1405
+ ```tsx
1406
+ function AuthScreen() {
1407
+ const machine = useAuthMachine()
1408
+ const state = useAtomSuspense(machine.result).value
1409
+
1410
+ return <MachineSummary snapshot={state} />
1411
+ }
1412
+ ```
1413
+
1414
+ That component rerenders for every result change. Prefer typed path selectors
1415
+ for state-owned UI.
1416
+
1417
+ Selection and equality belong to atoms, not to React hooks. To subscribe to
1418
+ part of a selected value, derive an atom from the path selector and give it the
1419
+ equality that defines a meaningful change. Declare the derivation once with
1420
+ `Atom.family`, keyed by the machine atom, so every render reuses the same atom:
1421
+
1422
+ ```tsx
1423
+ import { useAtomSuspense } from "@effect/atom-react"
1424
+ import { Equal, Option } from "effect"
1425
+ import { Atom } from "effect/reactivity"
1426
+
1427
+ type AuthMachineAtom = ReturnType<typeof useAuthMachine>
1428
+
1429
+ const editingEmail = Atom.family((machine: AuthMachineAtom) =>
1430
+ Atom.mapResult(
1431
+ AtomMachine.select(machine, "Editing"),
1432
+ Option.map(({ email }) => email)
1433
+ ).pipe(Atom.withEquality(Equal.equals))
1434
+ )
1435
+
1436
+ function EmailField() {
1437
+ const machine = useAuthMachine()
1438
+ const email = useAtomSuspense(editingEmail(machine)).value
1439
+
1440
+ return Option.match(email, {
1441
+ onNone: () => null,
1442
+ onSome: (email) => <input value={email} />
1443
+ })
1444
+ }
1445
+ ```
1446
+
1447
+ The component rerenders only when the projected email changes, not when other
1448
+ `Editing` fields change. Do not create a fresh derived atom on every render.
1449
+
1450
+ ### Share a keyed machine outside one React owner
1451
+
1452
+ `AtomMachine.family` is for registry-owned machines that unrelated consumers
1453
+ find by startup input. It is not the default for one React-owned workflow.
1454
+
1455
+ ```ts
1456
+ export const processAtoms = MachineAtoms.family(ProcessMachine, {
1457
+ atoms: {
1458
+ details: AtomMachine.select("Processing"),
1459
+ ready: AtomMachine.matches("Ready"),
1460
+ send: (machine) => machine.send
1461
+ }
1462
+ })
1463
+ ```
1464
+
1465
+ Consumers use the input as the shared identity key:
1466
+
1467
+ ```tsx
1468
+ const details = useAtomSuspense(processAtoms.details(input)).value
1469
+ const send = useAtomSet(processAtoms.send(input))
1470
+ ```
1471
+
1472
+ Each public projection retains its private machine owner. Keeping only
1473
+ `details(input)` or `send(input)` is safe. Do not return a weakly held composite
1474
+ scope and retain only one field from it.
1475
+
1476
+ Family keys use Effect `Equal` and `Hash` semantics. Keep them immutable. If a
1477
+ changing value should update one running workflow, model it as an event instead
1478
+ of changing the family key.
1479
+
1480
+ ### Module-owned machines
1481
+
1482
+ A no-input machine may intentionally have one module-owned identity:
1483
+
1484
+ ```ts
1485
+ export const CounterMachineAtom = MachineAtoms.make(CounterMachine)
1486
+ export const CounterStateAtom = AtomMachine.select(CounterMachineAtom, "Count")
1487
+ ```
1488
+
1489
+ Every consumer using the same `AtomRegistry` reaches the same running machine.
1490
+ Different registries still run independent instances.
1491
+
1492
+ ### Child machines
1493
+
1494
+ Direct child selectors follow the active child and preserve inactivity:
1495
+
1496
+ ```tsx
1497
+ const editor = machine.child(Editor)
1498
+ const editing = useAtomSuspense(
1499
+ AtomMachine.selectSnapshotChild(editor, "Editing")
1500
+ ).value
1501
+ ```
1502
+
1503
+ An inactive child or path returns `Option.none()`. Re-entry follows the
1504
+ replacement child instance. `MachineState` accepts the child bridge directly
1505
+ and renders `inactive` in both cases.
1506
+
1507
+ Use `AtomMachine.familyChild` when a parent owns a runtime-sized set of keyed
1508
+ children:
1509
+
1510
+ ```ts
1511
+ const Plant = Machine.childFamily(PlantMachine)
1512
+
1513
+ export const plantAtoms = AtomMachine.familyChild(CentralMachineAtom, {
1514
+ child: (plantId: string) => Plant(plantId),
1515
+ atoms: {
1516
+ broken: AtomMachine.matchesChild("Broken"),
1517
+ state: (plant) => plant.result,
1518
+ send: (plant) => plant.send
1519
+ }
1520
+ })
1521
+ ```
1522
+
1523
+ ### Generic helpers
1524
+
1525
+ Use `AtomMachine.MachineAtom.Any` and `AtomMachine.ChildMachineAtom.Any` to
1526
+ accept any bridge, including bridges for machines without events. Recover the
1527
+ exact types with the namespace extractors:
1528
+
1529
+ ```ts
1530
+ function StateView<A extends AtomMachine.MachineAtom.Any>(props: {
1531
+ readonly machine: A
1532
+ readonly render: (state: AtomMachine.MachineAtom.State<A>) => React.ReactNode
1533
+ }) {
1534
+ const state = useAtomSuspense(props.machine.result).value
1535
+ return props.render(state)
1536
+ }
1537
+
1538
+ type AuthEvent = AtomMachine.MachineAtom.Event<typeof AuthMachineAtom>
1539
+ type EditorState = AtomMachine.ChildMachineAtom.State<
1540
+ AtomMachine.ChildOf<typeof AuthMachineAtom, typeof Editor>
1541
+ >
1542
+ ```
1543
+
1544
+ ### Keep workflow effects out of emissions
1545
+
1546
+ Emissions are ephemeral notifications for observers. They are not replayed, so
1547
+ a subscriber that mounts late never sees an earlier emission. Do not drive work
1548
+ the workflow depends on, such as navigation, from emissions. Invoke that work
1549
+ from the state that requires it through a capability service, as in
1550
+ [Per-owner capabilities](#per-owner-capabilities); the machine then decides when
1551
+ it runs, what cancels it, and how failure changes the workflow.
1552
+
1553
+ An emission that only feeds UI feedback has two stream-atom details:
1554
+
1555
+ - `Atom.make(AtomMachine.emissions(machine))` publishes each emission as a
1556
+ waiting `Success`, then publishes the last emission again, no longer waiting,
1557
+ when the machine completes. Handlers must tolerate that repeated value.
1558
+ - `useAtomSubscribe(atom, f)` subscribes after commit without reading the atom.
1559
+ Pass `{ immediate: true }` so a lazy emissions atom starts; without it the
1560
+ callback never runs. The callback then also receives the initial result.
1561
+
1562
+ ### Registry and rendering semantics
1563
+
1564
+ A `MachineAtom` identifies one machine per `AtomRegistry`. Passing the same
1565
+ machine atom through two registry providers creates two independent runtimes.
1566
+ Unmounting a React owner releases its mount. The registry stops the machine
1567
+ after its final subscription and configured idle retention expire.
1568
+ `registry.dispose()` stops it immediately.
1569
+
1570
+ `useMachineAtom` does not start a machine during server rendering because
1571
+ React effects do not run on the server. Server reads never start a machine
1572
+ either. Every bridge atom carries an Effect Atom server value, which
1573
+ `@effect/atom-react` hooks read during server rendering and hydration, and
1574
+ `Atom.getServerValue` reads directly:
1575
+
1576
+ | Atom | Server value |
1577
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
1578
+ | `ref`, `send`, `stop` | `Initial` |
1579
+ | `snapshot` | `Success({ status: "active", state })`, waiting |
1580
+ | `result` | `Success(state)`, waiting |
1581
+ | `select`, `selectSnapshot`, `matches`, `can` | the projection of `state`, waiting |
1582
+ | `child(Child).result` and child projections | `Success(Option.some(childState))` when the planned state invokes `Child`, otherwise `Success(Option.none())` |
1583
+ | `family` and `familyChild` projections | the server value of the projected bridge atom |
1584
+
1585
+ `state` is the machine's planned startup state: the state `Machine.planInitial`
1586
+ settles into with the bridge's input, without running startup commands,
1587
+ invocations, or services. A resumed bridge uses its resumed snapshot. Children
1588
+ spawned at runtime or through child families are `Option.none()`. When the
1589
+ startup state cannot be planned synchronously, for example because the input
1590
+ is invalid, every server value is `Initial`. Each bridge plans at most once,
1591
+ on its first server read.
1592
+
1593
+ ### Server rendering and hydration
1594
+
1595
+ Render state slots with `MachineState` and no Suspense boundary:
1596
+
1597
+ ```tsx
1598
+ <Onboarding.Provider input={input}>
1599
+ <MachineState machine={Onboarding.useMachine()} path="Editing">
1600
+ {(editing) => <input value={editing.value.email} onChange={onChange} />}
1601
+ </MachineState>
1602
+ </Onboarding.Provider>
1603
+ ```
1604
+
1605
+ The server renders the planned `Editing` snapshot. Hydration renders the same
1606
+ markup, then the Provider mounts the machine and the same component tree
1607
+ receives live snapshots. The input keeps its DOM node, typed text, and focus.
1608
+
1609
+ Do not wrap hydrated forms in a Suspense boundary that a startup read can
1610
+ trigger. A suspended boundary replaces its server-rendered content with the
1611
+ fallback and later mounts new DOM nodes, discarding typed text and focus.
1612
+
1613
+ ## Effect Machine implementation review
1614
+
1615
+ Use this review after a machine and its UI adapter have been implemented. Look
1616
+ for modeling mistakes, redundant API usage, and logic that escaped the machine.
1617
+ Do not force a change when the current ownership is intentional.
1618
+
1619
+ Read [Effect Machine agent guide](#effect-machine-agent-guide) for statechart
1620
+ modeling and [Effect Atom and React](#effect-atom-and-react) for integration
1621
+ patterns.
1622
+
1623
+ Run the recommended rules from
1624
+ `@typeonce/oxlint-plugin-effect-machine` before
1625
+ the manual review. They catch provable duplicate invocation identities,
1626
+ asynchronous work, browser access, nondeterminism, conditional `stay`
1627
+ fallbacks, and one-use intermediate definitions in direct same-module machine
1628
+ definitions.
1629
+ Continue with this review for cross-module ownership and architectural
1630
+ questions that syntax alone cannot answer.
1631
+
1632
+ ### Review the responsibility boundaries
1633
+
1634
+ Use this split when deciding where code belongs:
1635
+
1636
+ | Layer | Owns |
1637
+ | ------------------ | ------------------------------------------------------------------------------- |
1638
+ | Machine | State, transitions, workflow decisions, effect lifetimes, and service execution |
1639
+ | Atoms | Reactive selection, projections, and keyed machine lookup |
1640
+ | Component | Rendering and translating user interaction into domain events |
1641
+ | `RegistryProvider` | An optional Atom registry ownership boundary |
1642
+
1643
+ If a component coordinates a workflow, an atom performs business work, or a
1644
+ provider has no ownership purpose, inspect that code more closely.
1645
+
1646
+ ### Keep ordinary transitions inline
1647
+
1648
+ Use `{ target: "Running" }` for a state with default construction.
1649
+ Use `{ target: "Running", data: ({ event }) => ({ count: event.count }) }`
1650
+ when the destination needs data. The checker rejects missing required fields.
1651
+ Use `decoded` for values already decoded by their schema.
1652
+
1653
+ Reserve `branches` and `resolve` for conditional outcomes or nested
1654
+ construction. List them on the transition itself; the resolver can select only
1655
+ the entries listed next to it. Use `commands` to enqueue work on an ordinary
1656
+ transition instead of adding a resolver. Use `reenter: true` when the source
1657
+ must restart.
1658
+ A `{ stay: true }` branch accepts its event, so `Machine.can` and
1659
+ `AtomMachine.can` return `true` when a resolver selects it. Review check: for
1660
+ every event that enables or disables a control, refuse it with `guard` or with
1661
+ `{ decline: true }` and `select.decline()`. Keep `stay` only for events that are
1662
+ deliberately accepted and ignored.
1663
+
1664
+ ### Choose React ownership or keyed family lookup
1665
+
1666
+ Use `useMachineAtom` when one React subtree owns the workflow, including a
1667
+ machine with startup input:
1668
+
1669
+ ```tsx
1670
+ const makeProcessMachine = machineAtoms.factory(processMachine)
1671
+ const machine = useMachineAtom(() => makeProcessMachine(input))
1672
+ ```
1673
+
1674
+ Pass the stable machine through props or Context. Startup input is captured
1675
+ once. Send an event to change the running workflow, or change the owner's React
1676
+ key to replace it.
1677
+
1678
+ Use `AtomMachine.family` when unrelated consumers must find one shared machine
1679
+ by its startup input. Effect Atom keeps a family value for an equal key while
1680
+ that returned value is reachable. Current runtimes may hold family values
1681
+ through `WeakRef`. Retaining one field from a composite family value does not
1682
+ retain the composite itself:
1683
+
1684
+ ```ts
1685
+ // Unsafe when consumers retain only stateAtom or sendAtom
1686
+ const processScope = Atom.family((input: ProcessInput) => {
1687
+ const machine = machineAtoms.make(processMachine, input)
1688
+ return {
1689
+ stateAtom: AtomMachine.select(machine, "process"),
1690
+ sendAtom: machine.send
1691
+ }
1692
+ })
1693
+ ```
1694
+
1695
+ `AtomMachine.family` returns direct atom families whose atoms retain the
1696
+ private machine bridge:
1697
+
1698
+ ```ts
1699
+ export const processAtoms = machineAtoms.family(processMachine, {
1700
+ atoms: {
1701
+ state: AtomMachine.select("process"),
1702
+ send: (machine) => machine.send
1703
+ }
1704
+ })
1705
+
1706
+ const stateAtom = processAtoms.state(input)
1707
+ const sendAtom = processAtoms.send(input)
1708
+ ```
1709
+
1710
+ No component `useMemo` is needed. The registry retains the public atom while a
1711
+ hook subscribes to it, and that atom retains the machine owner. Equal inputs
1712
+ use Effect `Equal` and `Hash` semantics and select the same family value.
1713
+
1714
+ For a no-input machine, use one module-level bridge or `useMachineAtom` in the
1715
+ owning React subtree. Do not add an unused family key.
1716
+
1717
+ Review check: search for composite `Atom.family` values that own a machine,
1718
+ `useMemo` around family lookup, repeated input propagation through one React
1719
+ subtree, and component-local calls to `machineAtoms.make` without a stable
1720
+ owner. Choose `AtomMachine.family` only when consumers need shared keyed
1721
+ lookup.
1722
+
1723
+ ### Justify each `RegistryProvider`
1724
+
1725
+ Effect Atom hooks use a shared default registry when no provider is present.
1726
+ Do not add `RegistryProvider` automatically.
1727
+
1728
+ Keep a provider when the subtree intentionally needs its own registry. Common
1729
+ reasons include:
1730
+
1731
+ - the same atom or machine descriptors must represent independent instances in
1732
+ separate subtrees;
1733
+ - the subtree owns registry disposal;
1734
+ - server rendering or hydration requires a request-local registry;
1735
+ - the registry needs initial values, custom scheduling, or custom idle
1736
+ settings.
1737
+
1738
+ Without one of those requirements, the default registry is enough:
1739
+
1740
+ ```tsx
1741
+ // A shared application instance can use the default registry.
1742
+ export function App() {
1743
+ return <ProcessScreen />
1744
+ }
1745
+ ```
1746
+
1747
+ Remember that adding or nesting a provider changes identity. The same atom
1748
+ descriptor stores separate state in each registry, so an unnecessary provider
1749
+ can split a machine that consumers expected to share.
1750
+
1751
+ Review check: for every `RegistryProvider`, state which registry boundary it
1752
+ creates and why. Remove it when there is no deliberate boundary.
1753
+
1754
+ ### Keep workflow logic in the machine
1755
+
1756
+ The machine owns business flow. Components render selected state and send
1757
+ domain events. Atoms adapt machine state for reactive consumers. Neither layer
1758
+ should coordinate the workflow.
1759
+
1760
+ The following component owns too much:
1761
+
1762
+ ```tsx
1763
+ const submit = async () => {
1764
+ send(OrderEvents.SubmitStarted())
1765
+ const order = await api.submitOrder(form)
1766
+ analytics.track("order submitted", { orderId: order.id })
1767
+ send(OrderEvents.SubmitSucceeded({ order }))
1768
+ }
1769
+ ```
1770
+
1771
+ Model `Submit` as the component-facing event. Let a machine state own the work
1772
+ and its lifetime:
1773
+
1774
+ ```ts
1775
+ // In make: effects: { submitOrder }
1776
+ machine.handle({
1777
+ states: {
1778
+ Editing: {
1779
+ on: {
1780
+ Submit: { target: "Submitting", data: ({ event }) => ({ order: event.order }) }
1781
+ }
1782
+ },
1783
+ Submitting: {
1784
+ invoke: {
1785
+ src: "submitOrder",
1786
+ input: ({ state }) => state.order,
1787
+ onDone: { target: "Complete", data: ({ output }) => ({ order: output }) },
1788
+ onFailure: { target: "Failed", data: ({ error }) => ({ message: String(error) }) }
1789
+ }
1790
+ }
1791
+ }
1792
+ })
1793
+ ```
1794
+
1795
+ `submitOrder` can use Effect services for the API request and analytics. The
1796
+ service implementation may live in its own module, but the machine decides
1797
+ when it runs, which state owns it, what cancels it, and how success or failure
1798
+ changes the workflow.
1799
+
1800
+ Apply the same test to browser APIs, storage, timers, analytics, navigation,
1801
+ and other effects. If the result or lifetime affects machine behavior, execute
1802
+ it through the machine. UI-only work such as focusing an element or measuring
1803
+ layout can remain in the component when it does not participate in the domain
1804
+ flow.
1805
+
1806
+ Review check: search components, hooks, and atom modules for service calls,
1807
+ `Effect.run*`, promises, browser APIs, analytics, timers, and chains of `send`
1808
+ calls. Move workflow coordination into states, transitions, and invoked work.
1809
+
1810
+ Per-instance capabilities, such as a router or a component callback, are
1811
+ services provided by the React owner, not schema fields or startup input. A
1812
+ function in state data or input cannot be encoded by `Machine.encodeSnapshot`.
1813
+ Review check: search schemas for `Schema.declare` guards that accept functions
1814
+ and move each one to a service, as in
1815
+ [Per-owner capabilities](#per-owner-capabilities). Do not
1816
+ drive navigation or other workflow effects from emissions.
1817
+
1818
+ ### Report findings
1819
+
1820
+ For each issue, cite the file and line, name the violated boundary, and show the
1821
+ smallest correction. Distinguish a confirmed problem from a provider or
1822
+ ownership choice that needs clarification. Do not rewrite correct code merely
1823
+ to match an example in this guide.