@typeonce/effect-machine 0.33.0 → 0.35.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 (137) hide show
  1. package/README.md +272 -628
  2. package/dist/Machine.d.ts +1076 -896
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +141 -90
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/childRegistry.d.ts +1 -1
  7. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  8. package/dist/internal/machine/cluster.d.ts +2 -50
  9. package/dist/internal/machine/cluster.d.ts.map +1 -1
  10. package/dist/internal/machine/cluster.js +4 -27
  11. package/dist/internal/machine/cluster.js.map +1 -1
  12. package/dist/internal/machine/clusterProtocol.d.ts +35 -0
  13. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
  14. package/dist/internal/machine/clusterProtocol.js +28 -0
  15. package/dist/internal/machine/clusterProtocol.js.map +1 -0
  16. package/dist/internal/machine/commandRuntime.d.ts +1 -1
  17. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  18. package/dist/internal/machine/configuration.d.ts +2 -2
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -64
  21. package/dist/internal/machine/configuration.js.map +1 -1
  22. package/dist/internal/machine/declaration.d.ts +17 -0
  23. package/dist/internal/machine/declaration.d.ts.map +1 -0
  24. package/dist/internal/machine/declaration.js +120 -0
  25. package/dist/internal/machine/declaration.js.map +1 -0
  26. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  27. package/dist/internal/machine/executionPlan.js +15 -22
  28. package/dist/internal/machine/executionPlan.js.map +1 -1
  29. package/dist/internal/machine/implementation.d.ts +34 -0
  30. package/dist/internal/machine/implementation.d.ts.map +1 -0
  31. package/dist/internal/machine/implementation.js +3 -0
  32. package/dist/internal/machine/implementation.js.map +1 -0
  33. package/dist/internal/machine/initialDeclaration.d.ts +14 -0
  34. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
  35. package/dist/internal/machine/initialDeclaration.js +137 -0
  36. package/dist/internal/machine/initialDeclaration.js.map +1 -0
  37. package/dist/internal/machine/invocation.d.ts +1 -1
  38. package/dist/internal/machine/invocation.d.ts.map +1 -1
  39. package/dist/internal/machine/invocation.js +1 -1
  40. package/dist/internal/machine/invocation.js.map +1 -1
  41. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  42. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  43. package/dist/internal/machine/machine.d.ts +13 -4
  44. package/dist/internal/machine/machine.d.ts.map +1 -1
  45. package/dist/internal/machine/machine.js +169 -388
  46. package/dist/internal/machine/machine.js.map +1 -1
  47. package/dist/internal/machine/planner.d.ts +8 -0
  48. package/dist/internal/machine/planner.d.ts.map +1 -1
  49. package/dist/internal/machine/planner.js +37 -78
  50. package/dist/internal/machine/planner.js.map +1 -1
  51. package/dist/internal/machine/process.d.ts +8 -7
  52. package/dist/internal/machine/process.d.ts.map +1 -1
  53. package/dist/internal/machine/process.js +16 -12
  54. package/dist/internal/machine/process.js.map +1 -1
  55. package/dist/internal/machine/protocol.d.ts +1 -1
  56. package/dist/internal/machine/protocol.d.ts.map +1 -1
  57. package/dist/internal/machine/protocol.js.map +1 -1
  58. package/dist/internal/machine/runtime.d.ts +2 -230
  59. package/dist/internal/machine/runtime.d.ts.map +1 -1
  60. package/dist/internal/machine/runtime.js +8 -1857
  61. package/dist/internal/machine/runtime.js.map +1 -1
  62. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  63. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeCompiled.js +867 -0
  65. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  66. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  68. package/dist/internal/machine/runtimeGeneric.js +471 -0
  69. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  71. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  72. package/dist/internal/machine/runtimeProtocol.js +561 -0
  73. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  74. package/dist/internal/machine/stateDefinition.d.ts +1 -1
  75. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  76. package/dist/internal/machine/stateDefinition.js +1 -13
  77. package/dist/internal/machine/stateDefinition.js.map +1 -1
  78. package/dist/internal/machine/targetReference.d.ts +15 -0
  79. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  80. package/dist/internal/machine/targetReference.js +41 -0
  81. package/dist/internal/machine/targetReference.js.map +1 -0
  82. package/dist/internal/machine/topology.d.ts.map +1 -1
  83. package/dist/internal/machine/topology.js +5 -3
  84. package/dist/internal/machine/topology.js.map +1 -1
  85. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  86. package/dist/internal/testing/machine/finiteModel.js +53 -46
  87. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  88. package/dist/internal/testing/machine/probe.js +1 -1
  89. package/dist/internal/testing/machine/probe.js.map +1 -1
  90. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/verification.js +7 -1
  92. package/dist/internal/testing/machine/verification.js.map +1 -1
  93. package/dist/testing/MachineTest.d.ts +105 -73
  94. package/dist/testing/MachineTest.d.ts.map +1 -1
  95. package/dist/testing/MachineTest.js +105 -73
  96. package/dist/testing/MachineTest.js.map +1 -1
  97. package/dist/unstable/cluster/ClusterMachine.d.ts +18 -13
  98. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  99. package/dist/unstable/cluster/ClusterMachine.js +18 -25
  100. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  101. package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
  102. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  103. package/dist/unstable/reactivity/AtomMachine.js +41 -24
  104. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  105. package/docs/agent-guide.md +66 -91
  106. package/docs/machine-review.md +19 -49
  107. package/docs/root-api.md +62 -62
  108. package/package.json +1 -1
  109. package/src/Machine.ts +1836 -2907
  110. package/src/internal/machine/childRegistry.ts +1 -1
  111. package/src/internal/machine/cluster.ts +7 -73
  112. package/src/internal/machine/clusterProtocol.ts +56 -0
  113. package/src/internal/machine/commandRuntime.ts +1 -1
  114. package/src/internal/machine/configuration.ts +53 -65
  115. package/src/internal/machine/declaration.ts +140 -0
  116. package/src/internal/machine/executionPlan.ts +16 -22
  117. package/src/internal/machine/implementation.ts +41 -0
  118. package/src/internal/machine/initialDeclaration.ts +157 -0
  119. package/src/internal/machine/invocation.ts +3 -3
  120. package/src/internal/machine/invocationDefinition.ts +1 -1
  121. package/src/internal/machine/machine.ts +225 -576
  122. package/src/internal/machine/planner.ts +84 -118
  123. package/src/internal/machine/process.ts +40 -33
  124. package/src/internal/machine/protocol.ts +3 -3
  125. package/src/internal/machine/runtime.ts +20 -3037
  126. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  127. package/src/internal/machine/runtimeGeneric.ts +799 -0
  128. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  129. package/src/internal/machine/stateDefinition.ts +1 -15
  130. package/src/internal/machine/targetReference.ts +55 -0
  131. package/src/internal/machine/topology.ts +5 -3
  132. package/src/internal/testing/machine/finiteModel.ts +58 -53
  133. package/src/internal/testing/machine/probe.ts +1 -1
  134. package/src/internal/testing/machine/verification.ts +7 -1
  135. package/src/testing/MachineTest.ts +105 -73
  136. package/src/unstable/cluster/ClusterMachine.ts +22 -25
  137. package/src/unstable/reactivity/AtomMachine.ts +41 -24
package/README.md CHANGED
@@ -42,716 +42,359 @@ in lockstep with this package.
42
42
 
43
43
  ## Quick start
44
44
 
45
- Start with events and root-owned data. A data-only machine needs no child states:
45
+ Declare the root once, derive its references, then add behavior with event maps:
46
46
 
47
47
  ```ts
48
48
  import { Machine } from "@typeonce/effect-machine"
49
49
  import { Effect, Schema } from "effect"
50
-
51
50
  const Root = Machine.state({ fields: { count: Schema.Number } })
51
+ const targets = Machine.targets(Root)
52
52
  const Events = Machine.events({ Increment: { by: Schema.Number } })
53
- const CounterDefinition = Machine.make({
53
+ const Counter = Machine.make({
54
54
  root: Root,
55
- events: Events,
56
- initial: (root) => root.from(() => ({ count: 0 }))
57
- })
58
- const Counter = CounterDefinition.handle({
55
+ events: Events
56
+ }).handle({
57
+ root: () => ({ count: 0 }),
59
58
  on: {
60
- Increment: (to) =>
61
- to.self.update.from(({ current, event }) => ({
62
- count: current.count + event.by
63
- }))
59
+ Increment: {
60
+ update: targets.root,
61
+ data: ({ root, event }) => ({ count: root.count + event.by })
62
+ }
64
63
  }
65
64
  })
66
-
67
65
  const program = Effect.scoped(Effect.gen(function*() {
68
66
  const ref = yield* Machine.start(Counter)
69
67
  yield* ref.send(Events.Increment({ by: 1 }))
70
68
  }))
71
69
  ```
72
70
 
73
- `self.update` replaces the owner's complete value without exiting and reentering
74
- it. Its children and scoped work remain active. Add `initial` and `states` to
75
- the same root descriptor when the workflow needs distinct modes; the root data
76
- survives transitions between those children.
77
-
78
- See [the root API guide](./docs/root-api.md) for topology-only machines,
79
- initialization, reusable schemas, guards, migration, and observation contracts.
80
-
81
- `handle` creates a complete implementation boundary. Its result does not
82
- expose `handle`, so all behavior for one machine belongs in the same handler
83
- tree. Reuse the definition when multiple independent implementations are
84
- useful, such as production and testing variants:
85
-
86
- ```ts
87
- const ProductionCounter = CounterDefinition.handle(productionHandlers)
88
- const TestingCounter = CounterDefinition.handle(testingHandlers)
89
- ```
90
-
91
- `Machine.start` returns a `MachineRef` with `send`, `state`, `snapshot`,
92
- `changes`, `emissions`, `join`, and `stop`. Sending enqueues an event; observe
93
- `changes` or use the testing probe when work must be causally acknowledged.
71
+ Root data is shared state. `update: targets.root` replaces that value while
72
+ retaining the active child configuration and its running work. Ordinary
73
+ transitions target a descendant; the root itself is not a destination.
94
74
 
95
75
  ## Modeling workflow
96
76
 
97
- 1. Define reusable domain schemas where they express a domain boundary.
98
- 2. Declare one root with `Machine.state`. Use inline children or mount reusable
99
- descriptors under `states`. `fields` builds a tagged schema; `schema` keeps
100
- an existing schema and its construction behavior.
101
- 3. Declare field records with `Machine.events`, `Machine.internalEvents`, and
102
- `Machine.emittedEvents`. Import existing tagged unions or tagged classes with
103
- the corresponding `eventsFromSchemas`, `internalEventsFromSchemas`, or
104
- `emittedEventsFromSchemas` constructor.
105
- 4. Pass the root descriptor to `Machine.make({ root, events })`. Supply root
106
- values with `initial`; declared child defaults determine startup topology.
107
- 5. Implement root behavior directly in `handle`, with child behavior in its
108
- `states` property. Add runtime, Atom, testing, or Cluster adapters at the
109
- application boundary.
110
-
111
- The root has path `""`; children retain paths such as `Editing` and
112
- `Editing.Form`. Use `Root.path(...)` to validate path literals. Type full
113
- snapshots as `Machine.Snapshot<typeof Root>` or `Machine.Snapshot<typeof machine>`,
114
- state values as `Machine.Value<typeof Root, Path>`, and selected snapshots as
115
- `Machine.SnapshotAt<typeof Root, Path>`.
116
-
117
- ### Make invalid states unrepresentable
118
-
119
- Treat topology as a domain contract, not as file organization. A parallel state
120
- declares the full Cartesian product of its regions, so use it only when every
121
- combination has a coherent meaning. If one region must inspect another before
122
- entering a state safely, prefer a compound hierarchy that makes the forbidden
123
- combination impossible. `matches` remains useful for views, tests, and genuine
124
- coordination between independent regions; it should not repair an invalid
125
- state product.
126
-
127
- Keep state-scoped Effects beneath the state that guarantees their resources,
128
- and enforce command availability in the machine rather than only by disabling
129
- UI controls. When entering an inactive compound or parallel state's declared
130
- default, select `.initial`; explicitly construct descendants only for a
131
- non-default configuration or a complete replacement of an already-active
132
- parallel root.
133
-
134
- ### Construct state through builders
135
-
136
- Use `.from(...)` when constructing a new state from schema make input:
137
-
138
- ```ts
139
- target.from({ draft: event.draft })
140
- ```
141
-
142
- The machine runs these inputs through the state schema while planning. Schema
143
- defaults, transformations, refinements, and tagged-class identity are
144
- therefore preserved, and decode failures remain typed machine failures. This
145
- is the default construction path.
146
-
147
- Use `.decoded(...)` when the value is already a `Schema.Type`:
148
-
149
- ```ts
150
- target.decoded(new Ready({ notice: null }))
151
- ```
152
-
153
- The machine still validates the value against the schema's type side. It does
154
- not run encoded-input transformations again. State builders are not callable;
155
- the method name always makes the construction mode visible.
77
+ Put data on the lowest state that owns it. Use tagged schemas or `fields` for
78
+ state-owned values and `{}` for structural states. Prefer distinct states over
79
+ boolean flags that allow impossible combinations. Put shared behavior on the
80
+ lowest common ancestor, and reserve parallel states for independent modes.
156
81
 
157
- When sibling states share fields, remove the source discriminator and pass the
158
- remaining fields through the target schema:
82
+ `Machine.state` declares topology. `Machine.make` captures protocols, startup
83
+ input, sources, and named branch groups. `.handle` implements behavior in one
84
+ nested object and returns an executable machine. One definition can create
85
+ independent implementations by calling `.handle` more than once.
159
86
 
160
- ```ts
161
- const handlers = {
162
- Submit: (to) =>
163
- to.local.Saving().resolve(({ state, target }) => {
164
- const { _tag: _, ...fields } = state
165
- return target.from({ ...fields, attempt: 1 })
166
- })
167
- }
168
- ```
87
+ ### Declare startup data and initial edges
169
88
 
170
- Omit `schema` when a state represents control flow but owns no data. Use `{}`
171
- instead of defining an empty tagged schema:
89
+ The root descriptor contains schemas and hierarchy. `make` registers protocols
90
+ and programs. `.handle` selects initial children and constructs their values:
172
91
 
173
92
  ```ts
174
- const States = Machine.state({
175
- initial: "Form",
93
+ const Root = Machine.state({
94
+ fields: { seed: Schema.Number },
176
95
  states: {
177
- Form: {
178
- initial: "Editing",
179
- states: {
180
- Editing: {},
181
- Saving
182
- }
183
- }
96
+ Loading: { fields: { count: Schema.Number } },
97
+ Ready: {}
184
98
  }
185
99
  })
186
-
187
- const definition = Machine.make({
188
- root: States,
189
- events: Machine.eventsFromSchemas(),
190
- initialConfiguration: (root) =>
191
- root.resolve(({ target }) => target.from((to) => to.Form.from((form) => form.Editing.from())))
100
+ const targets = Machine.targets(Root)
101
+ const machine = Machine.make({ root: Root, input: Schema.Number, events: Machine.events({}) }).handle({
102
+ root: ({ input }) => ({ seed: input }),
103
+ initial: { target: targets.root.Loading, data: ({ root }) => ({ count: root.seed }) }
192
104
  })
193
105
  ```
194
106
 
195
- Schema-less states remain active, targetable, matchable, and visible through
196
- `getSnapshot`, but have no value to read. Their builders expose only `.from`,
197
- their handler `state` is `undefined`, and `get` / `getWithParents` accept only
198
- schema-backed paths. Add a schema later if the state starts owning data.
199
-
200
- Keep data-bearing state schemas together in a named `Schema.TaggedUnion` and
201
- reference its cases from the topology. For a standalone state schema whose
202
- class identity is useful, declare a named `Schema.TaggedClass`. Do not bury
203
- inline `fields` in a `Machine.state` descriptor.
204
-
205
- Put data on the narrowest state where it is valid. If sibling phases share
206
- data, put it on their compound parent.
207
-
208
- ### Separate inputs, raised events, and emissions
107
+ Only the root constructor receives startup input. Child constructors receive
108
+ root data, their owning state's data, ancestors, and the lifecycle event.
109
+ Each compound declares an initial edge targeting one direct child; that edge
110
+ also supplies the child's required values. Nested compounds declare their own
111
+ edges in their handlers. There is no separate `initialConfiguration` override.
209
112
 
210
- `events` is the public machine-input protocol. Events raised to the same machine
211
- belong in `internalEvents`. Ephemeral outward notifications have their own
212
- `emittedEvents` protocol:
113
+ A parallel handler's `initial` is a map of region data. It enters all regions:
213
114
 
214
115
  ```ts
215
- export const CommandEvent = Machine.eventsFromSchemas(
216
- Schema.TaggedUnion({ Save: {} })
217
- )
218
- export type PublicCommandEvent = Machine.EventOf<typeof CommandEvent>
219
- const InternalEvent = Machine.internalEventsFromSchemas(
220
- Schema.TaggedUnion({
221
- Saved: { id: Schema.String },
222
- SaveFailed: { message: Schema.String }
223
- })
224
- )
225
- const Emissions = Machine.emittedEventsFromSchemas(
226
- Schema.TaggedUnion({
227
- SaveObserved: { id: Schema.String }
228
- })
229
- )
230
-
231
- const definition = Machine.make({
232
- root: States,
233
- events: CommandEvent,
234
- internalEvents: InternalEvent,
235
- emittedEvents: Emissions,
236
- initial: (to) => to.Idle()
116
+ const Root = Machine.state({
117
+ type: "parallel",
118
+ states: {
119
+ Editor: { fields: { draft: Schema.String }, states: { Editing: {}, Saved: {} } },
120
+ Network: { fields: { online: Schema.Boolean } }
121
+ }
122
+ })
123
+ const targets = Machine.targets(Root)
124
+ const machine = Machine.make({ root: Root, events: Machine.events({}) }).handle({
125
+ initial: { Editor: { draft: "" }, Network: { online: false } },
126
+ states: { Editor: { initial: { target: targets.root.Editor.Editing } } }
237
127
  })
238
128
  ```
239
129
 
240
- Handlers see both protocols. Typed `send`, `Machine.can`, and `Machine.plan`
241
- accept only public events. Event tags must be unique and public/internal tags
242
- must be disjoint.
243
-
244
- Export the descriptor returned by `Machine.events` instead of exporting its
245
- schemas. This keeps the deferred constructors as the standard way to create
246
- events without exposing schema `.make` methods:
247
-
248
- ```ts
249
- ref.send(CommandEvent.Save())
250
- enqueue.raise(InternalEvent.Saved({ id: "entry-1" }))
251
- enqueue.emit(Emissions.SaveObserved({ id: "entry-1" }))
252
- ```
253
-
254
- The returned constructors preserve each schema's make input, including required
255
- fields and constructor defaults. They defer schema construction until delivery,
256
- so invalid values fail planning or the running machine with
257
- `MachineSchemaDecodeError` instead of throwing at the call site.
258
- Schemas with an open discriminator such as `_tag: Schema.String` remain valid
259
- protocols but cannot expose a finite constructor set; pass a complete event
260
- object to `send` or `Machine.plan` for those events.
261
-
262
- `ref.emissions` is a hot `Stream`: it publishes only notifications produced
263
- after subscription, replays nothing, and completes when the machine terminates.
264
- Snapshots remain separate and stateful: `ref.changes` begins with the current
265
- lifecycle snapshot and then follows later changes. Use `Machine.prepare` when
266
- an observer must be installed before initial-entry actions run:
267
-
268
- ```ts
269
- const prepared = yield * Machine.prepare(machine)
270
-
271
- yield * prepared.emissions.pipe(
272
- Stream.runForEach(handleEmission),
273
- Effect.forkScoped({ startImmediately: true })
274
- )
275
-
276
- const ref = yield * prepared.start
277
- ```
278
-
279
- `Machine.start(machine)` remains the one-step convenience for callers that do
280
- not observe startup emissions. Preparation does not retain or replay an
281
- emission: the observer is simply subscribed before initialization begins.
282
-
283
- ### Inspect a live machine tree
284
-
285
- `Machine.prepare(machine).inspection` is the operational counterpart to the
286
- domain-facing `changes` and `emissions` streams. It observes the prepared root
287
- and every locally owned child, `Logic` process, Effect, and timer in one total
288
- publication order:
289
-
290
- ```ts
291
- const prepared = yield * Machine.prepare(checkout)
292
-
293
- yield * prepared.inspection.pipe(
294
- Stream.runForEach((record) => Console.log(record.sequence, record.subject.id, record._tag)),
295
- Effect.forkScoped({ startImmediately: true })
296
- )
130
+ Root and region data accept the short literal or callback form. For decoded
131
+ values, use `{ decoded: true, data: valueOrCallback }`. This descriptor accepts
132
+ only those two keys. If your domain data itself has `decoded: true` and `data`
133
+ fields, return it from a callback: callback results are always ordinary schema
134
+ input. Required data is checked at compile time; schema-less regions accept no data.
297
135
 
298
- const checkoutRef = yield * prepared.start
299
- ```
136
+ Use root or state `entry`/`exit` for synchronous commands and `invoke` for
137
+ asynchronous work. Constructors only produce values. An unhandled definition
138
+ cannot be started, planned, or registered as a child machine.
300
139
 
301
- For a handled input, the stream may expose values such as:
140
+ ### Construct state values
302
141
 
303
142
  ```ts
304
- { _tag: "EventSent", sequence: 2, deliveryId: 0,
305
- subject: { id: "checkout", sessionId: "machine:0", kind: "Machine" },
306
- source: undefined, target: { id: "checkout", sessionId: "machine:0" },
307
- event: CheckoutEvents.Submit(), causedBy: undefined }
308
-
309
- { _tag: "EventProcessed", sequence: 4, macrostepId: 0,
310
- deliveryId: 0, handled: true, configurationChanged: true,
311
- before: { status: "active", state: /* ... */ },
312
- after: { status: "active", state: /* ... */ }, microsteps: [/* ... */] }
313
- ```
314
-
315
- The closed `Machine.Inspection.Event` union also reports creation,
316
- initialization and startup failure, direct `Logic` state updates, outward
317
- emissions, Effect/timer activity lifecycles, and termination. Records erase
318
- unrelated child protocols to `unknown`; application-level observation remains
319
- typed through each reference's `changes` and `emissions`.
320
-
321
- The stream is hot, non-replayed, never fails, and completes after the root
322
- terminates. Subscribe before `prepared.start` to capture initialization. Local
323
- session ids are unique only inside that prepared ownership tree: `machine:0`
324
- is the root and later ids identify its descendants. They are intentionally not
325
- distributed identities. Cluster placement, routing, and correlation continue
326
- to use Cluster entity, runner, and request identities at the integration
327
- boundary.
328
-
329
- `AtomMachine.inspection(machineAtom)` provides the same root-scoped stream and
330
- starts a fresh atom-backed machine only after its inspection subscription is
331
- installed.
332
-
333
- Invalid event and emission constructions fail the machine with a typed
334
- `MachineSchemaDecodeError`; they do not throw from the constructor call.
335
-
336
- ### Send explicitly between machines
337
-
338
- `raise` targets the current machine in the same macrostep. `sendTo` targets a
339
- machine mailbox and is processed later. A machine that requires an owner
340
- declares the subset of parent inputs it may send with `Machine.parent`:
341
-
342
- ```ts
343
- const ParentEvents = Machine.eventsFromSchemas(ChildFinished)
344
-
345
- const child = Machine.make({
346
- root: ChildStates,
347
- events: ChildEvents,
348
- parent: Machine.parent(ParentEvents),
349
- initial: (to) => to.Working()
143
+ const Root = Machine.state({
144
+ states: {
145
+ Idle: {},
146
+ Loading: { fields: { query: Schema.String } },
147
+ Ready: { fields: { items: Schema.Array(Schema.String) } },
148
+ Failed: { fields: { message: Schema.String } }
149
+ }
150
+ })
151
+ const targets = Machine.targets(Root)
152
+ const Events = Machine.events({ Search: { query: Schema.String }, Reset: {} })
153
+ const Search = Machine.make({
154
+ root: Root,
155
+ events: Events
350
156
  }).handle({
157
+ initial: {
158
+ target: targets.root.Idle
159
+ },
351
160
  states: {
352
- Working: {
161
+ Idle: {
353
162
  on: {
354
- Finish: (to) =>
355
- to.branch.Done().resolve(({ parent, target }, enqueue) => {
356
- enqueue.sendTo(parent, ParentEvents.ChildFinished({ id: "job-1" }))
357
- return target.from()
358
- })
163
+ Search: {
164
+ target: targets.root.Loading,
165
+ data: ({ event }) => ({ query: event.query })
166
+ }
359
167
  }
360
168
  },
361
- Done: {}
169
+ Loading: { on: { Reset: { target: targets.root.Idle } } },
170
+ Ready: {},
171
+ Failed: {}
362
172
  }
363
173
  })
364
-
365
- const Child = Machine.child("worker", child)
366
- const ParentInputs = Machine.eventsFromSchemas(Start, ParentEvents)
367
174
  ```
368
175
 
369
- `parent` is statically present in every child callback, and root APIs such as
370
- `Machine.start`, `Machine.planInitial`, Atom machines, and Cluster machines
371
- reject this machine. When `Child` is invoked, the parent definition must accept
372
- every declared parent event; otherwise `.handle(...)` is a compile-time error.
373
- Inside the child, the parent target accepts only those declared events.
374
-
375
- Use `parent: Machine.optionalParent(ParentEvents)` when the same machine is
376
- intentionally valid both as a root and as a child. In that case `parent` is
377
- `MachineTarget<...> | undefined` and must be narrowed before sending. When no
378
- parent declaration is present, callbacks do not expose a `parent` property.
379
- `emit` never sends to the parent: it only publishes on the emitting machine's
380
- `emissions` stream.
381
-
382
- Every handler also receives `self`, which can be targeted with `sendTo` when a
383
- later mailbox turn is required. Use `raise` instead for same-macrostep work.
384
- Both `self` and `parent` are minimal `Machine.MachineTarget<Event>` values. The
385
- shared `Machine.MachineReferences<InputEvents, ParentEvents>` context keeps
386
- their input protocols separate without exposing snapshot or lifecycle APIs.
387
- Structural state values use distinct names: `containingState` is the immediate
388
- valued state in the same statechart, while `ancestors` maps valued ancestor
389
- paths. `parent` always means the owning machine target.
390
-
391
- ### Choose the target by scope
392
-
393
- | Builder | Use when | Preserves |
394
- | ---------------- | ---------------------------------------- | ------------------------------------------------- |
395
- | `target.none()` | Handling without selecting a destination | The complete current configuration |
396
- | `target.local` | Moving inside the nearest compound scope | Ancestors and unrelated parallel regions |
397
- | `target.branch` | Moving elsewhere under the active root | Omitted active ancestors and parallel regions |
398
- | `target.full` | Replacing or selecting a complete root | Nothing implicit for a newly selected root |
399
- | `target.history` | Restoring a declared history node | The remembered configuration or its typed default |
400
-
401
- Every required transition handler selects a target from its inline `to`
402
- builder. Return a bare selection such as `to.local.Idle()` when the selected
403
- builder supports zero-argument construction; the machine applies the same
404
- default construction as `target.from()`. This includes empty schemas and
405
- schemas whose constructor fields are all optional or defaulted. TypeScript
406
- rejects the bare form when state data or nested configuration is required.
407
- Call `.resolve(...)` when construction depends on handler context or the
408
- transition needs to enqueue commands. An absent handler ignores the trigger; `to.none` handles
409
- it and retains queued commands, raised events, and emitted events without
410
- selecting a destination. Concrete destinations stay narrowed inside their
411
- resolver, and `to.branches({...})` gives the resolver only the declared named
412
- `select` builders. Builders describe the
413
- next logical configuration. Shared states exit and enter only when paths
414
- change; call `.reenter()` before `.from(...)`, `.decoded(...)`, or `.resolve(...)`
415
- when the source must restart. Default-constructible targets can finish at
416
- `.reenter()`. With `to.none`, reentry
417
- restarts the source while retaining its configuration.
418
-
419
- Topology-only definition instructions are values: `to.none`, declared
420
- `.initial` and history selections, and `to.local.with`. Concrete state and
421
- choice destinations remain calls such as `to.local.Running()`. Runtime named
422
- branch builders remain callable, including `select.unchanged()`, because their
423
- result carries the selected branch evidence.
424
-
425
- ### Update an active scope value
426
-
427
- Use `to.local.update(...)` to replace the value owned by the nearest active
428
- compound scope without rebuilding its active child. Use
429
- `to.branch.<path>.update(...)` for a valued compound or parallel ancestor of the
430
- handler source:
176
+ `data` accepts a value or a synchronous callback returning the schema's make
177
+ input, including constructor defaults and transformations. Add `decoded: true`
178
+ when supplying the already-decoded type, including class instances. Both paths
179
+ validate values and report `MachineSchemaDecodeError`. Omit data only when the
180
+ selected state supports empty construction. Schema-less states do not accept data.
431
181
 
432
- ```ts
433
- const handlers = {
434
- Increment: (to) => to.branch.root.session.update.from(({ current }) => ({ count: current.count + 1 }))
435
- }
436
- ```
182
+ A callback receives the specific event and source-state types, plus `root`,
183
+ `containingState`, `ancestors`, and the appropriate machine references. A
184
+ transition callback also receives the current logical `snapshot`. There is no
185
+ unrestricted destination builder in the callback.
437
186
 
438
- The update keeps the exact active descendants, their values, history records,
439
- completion outputs, and unrelated parallel regions. It runs no exit or entry
440
- actions and does not restart state-owned work. Eventless stabilization still
441
- runs, so an `always` transition can react to the new value.
187
+ ### Declare advanced and conditional transitions
442
188
 
443
- The plain update method remains useful when topology does not change. It is
444
- also a static selection for a named branch:
189
+ A resolver that chooses a branch, constructs nested children, or enqueues
190
+ commands uses a named group in `make`. The group captures every possible edge
191
+ before any resolver executes:
445
192
 
446
193
  ```ts
447
- to.branches({
448
- changed: { target: to.local.update },
449
- unchanged: { target: to.none }
450
- }).resolve(({ select, event }) =>
451
- event.changed
452
- ? select.changed.from({ count: event.count })
453
- : select.unchanged()
454
- )
455
- ```
456
-
457
- ### Change topology and a retained owner together
458
-
459
- When a transition enters another child and also replaces a valued ancestor
460
- that stays active, declare both operations on the same target:
461
-
462
- ```ts
463
- const handlers = {
464
- CreatePlan: (to) =>
465
- to.local.SavingPlan()
466
- .updating(to.branch.Ready)
467
- .from(({ current, event }) => ({
468
- target: { request: { _tag: "Create", input: event.input } },
469
- update: { ...current, notice: null }
470
- }))
471
- }
194
+ const machine = Machine.make({
195
+ root: Root,
196
+ events: Events,
197
+ branches: {
198
+ search: {
199
+ loading: { target: targets.root.Loading, title: "Query supplied" },
200
+ idle: { target: targets.root.Idle, title: "Empty query" }
201
+ }
202
+ }
203
+ }).handle({
204
+ initial: { target: targets.root.Idle },
205
+ states: {
206
+ Idle: {
207
+ on: {
208
+ Search: {
209
+ branches: "search",
210
+ resolve: ({ event, select }) =>
211
+ event.query.length > 0
212
+ ? select.loading.from({ query: event.query })
213
+ : select.idle.from()
214
+ }
215
+ }
216
+ }
217
+ }
218
+ })
472
219
  ```
473
220
 
474
- `to.local.SavingPlan()` selects topology. `.updating(to.branch.Ready)` names
475
- the retained valued owner and makes its replacement mandatory. `.from(...)`
476
- returns `{ target, update }` with constructor inputs for both values;
477
- `.decoded(...)` returns already decoded values for both. `current` is that
478
- owner's decoded value from the pre-transition snapshot. Use `.resolve(...)`
479
- when constructing explicit children, mixing construction methods, or queuing
480
- commands; its `target` and `owner` builders construct the two values.
221
+ Each selector is bound to its declared destination. Its constructor rejects a
222
+ payload belonging to another branch. A single-target group works the same way;
223
+ there is no second path declaration in the resolver. For a compound target,
224
+ `select.checkout.from(parentValues, child => child.Review.from(childValues))`
225
+ constructs the explicitly selected subtree. Parallel constructors require every
226
+ entered region. Every compound has an initial edge, including inactive branches. Final outputs,
227
+ history defaults, and choices remain part of machine readiness checking.
481
228
 
482
- The topology change and owner replacement apply atomically in one microstep.
483
- The owner does not exit or reenter, its work is not restarted, and destination
484
- entry actions observe the new owner value. Eventless stabilization follows.
485
- Only one retained owner may be replaced by a combined target. A `full` target,
486
- or any target that exits the selected owner, does not expose `.updating`.
487
- Named branches support value-only updates; a combined update declares its
488
- destination directly.
229
+ Use `guard: context => boolean` to decline before construction or commands.
230
+ For a resolver that can decline, explicitly add `declinable: true`; only then may
231
+ it return `context.decline()`. `reenter: true` restarts the handler's source
232
+ where that operation supports reentry. A retained source-value update does not
233
+ restart its lifecycle.
489
234
 
490
- For a schema-less destination, construction remains explicit:
235
+ ### Select destinations and retain owners
491
236
 
492
- ```ts
493
- to.local.Idle()
494
- .updating(to.branch.Ready)
495
- .resolve(({ current, output, owner, target }) =>
496
- target.from().update(
497
- owner.decoded(
498
- new Ready({
499
- ...current,
500
- day: output,
501
- notice: "Plan changed."
502
- })
503
- )
504
- )
505
- )
506
- ```
507
-
508
- Both values derive from the same pre-transition snapshot and are validated
509
- before lifecycle actions run. Competing transitions that write the same owner
510
- conflict; document order and hierarchy select one writer rather than applying
511
- last-write-wins behavior.
237
+ All references come from the same root descriptor supplied to `make`:
512
238
 
513
- Use `.guard(predicate)` before construction to decline an update without
514
- constructing values or queuing commands. It is available on standalone and
515
- combined updates. A false guard allows ancestor fallback. A resolver may also
516
- return `decline()` with `{ declinable: true }` for decisions during resolution.
517
- Call `.reenter()` before construction on event or invocation transitions when
518
- the handler source should exit and enter again. Reentry applies to that source,
519
- not to the retained ancestor whose value changed.
239
+ | Declaration | Meaning |
240
+ | ----------------------------------------------------- | ------------------------------------------------------------------------- |
241
+ | `{ target: targets.root.Checkout.Review, data: ... }` | Enter a declared destination with its value. |
242
+ | `{ initial: targets.root.Checkout, data: ... }` | Enter the declared initial configuration of a compound or parallel state. |
243
+ | `{ history: targets.root.Checkout.recent }` | Restore a declared history state. |
244
+ | `{ update: targets.root.Checkout, data: ... }` | Replace a retained active owner's value. |
245
+ | `{ update: targets.root, data: ... }` | Replace root data and retain active descendants. |
246
+ | `{ none: true }` | Accept an event without changing the configuration. |
520
247
 
521
- The selector omits `update` for schema-less scopes, atomic and final states,
522
- inactive branches, parallel sibling regions, and choice resolvers. Updating a
523
- parallel sibling requires an event handled by that region.
524
-
525
- Use `declinable: true` when a resolver may decide that its transition is not
526
- enabled. Only that resolver receives `decline()`, and its return type expands to
527
- accept the opaque declined result:
248
+ An atomic transition can enter a destination and update one retained owner:
528
249
 
529
250
  ```ts
530
- const handlers = {
531
- Submit: (to) =>
532
- to.local.Saving().resolve(
533
- ({ event, target, decline }) => accepts(event) ? target.from({ draft: event.draft }) : decline(),
534
- { declinable: true }
535
- )
251
+ Save: {
252
+ target: targets.root.Checkout.Saving,
253
+ update: targets.root.Checkout,
254
+ data: ({ event, ancestors }) => ({
255
+ target: { request: event.request },
256
+ update: { ...ancestors.Checkout, revision: event.revision }
257
+ })
536
258
  }
537
259
  ```
538
260
 
539
- Declining discards work enqueued by that resolver. Event and eventless dispatch
540
- continues with the next eligible ancestor; if no candidate accepts, no
541
- transition is selected. This differs from `target.none()`, which consumes the
542
- trigger and prevents an ancestor from handling it. `transitionDefinitions`
543
- reports each handler's `acceptance` as `"required"` or `"declinable"` while
544
- preserving the exact declared target branches. Choices and initial routing must
545
- remain total and cannot use declinable transitions. Completion and invocation
546
- outcomes have no ancestor candidate: declining one ignores that lifecycle
547
- occurrence and leaves the current configuration active.
261
+ The complete replacement values are validated before either change is applied.
262
+ Advanced construction declares both references in a branch and uses
263
+ `select.saved.from(destinationValues).update.from(ownerValues)`.
264
+ A retained owner must be active for that source and remain active through the
265
+ transition. A sibling region's value cannot be updated through this operation.
548
266
 
549
- Use `Machine.can` when a caller needs to test a concrete event against a
550
- snapshot. The direct and machine-specialized forms have the same semantics:
267
+ The runtime transition API does not replace arbitrary complete root
268
+ configurations. Startup follows the initial declarations in `.handle`; history
269
+ defaults retain complete subtree construction for restoration.
551
270
 
552
- ```ts
553
- const canSubmit = yield * Machine.can(machine, snapshot, Submit({ draft }))
271
+ ### Protocols and ownership
554
272
 
555
- const canMachine = Machine.can(machine)
556
- const canCancel = yield * canMachine(snapshot, Cancel())
557
- ```
273
+ `Machine.events` defines public messages. `Machine.internalEvents` adds
274
+ machine-local raised events; `Machine.emittedEvents` defines notifications.
275
+ Their `FromSchemas` counterparts accept existing tagged schemas. Public and
276
+ internal tags must be disjoint. Deferred event constructors are validated when
277
+ the runtime receives the event.
558
278
 
559
- `can` returns `true` when at least one required or non-declined handler accepts
560
- the event. Targetless transitions count as accepted. Invalid event input fails
561
- with `MachineSchemaDecodeError`; a valid unhandled event returns `false`.
562
- Declinable resolvers run to decide acceptance, but collected commands,
563
- emissions, and raised events are discarded. Required resolvers and transition
564
- lifecycle do not run.
279
+ Declare `parent: Machine.parent(events)` for a required owner protocol, or
280
+ `Machine.optionalParent(events)` for a machine that may run independently.
281
+ Handlers receive typed `self` and, when declared, `parent` references. Resolvers
282
+ use their second `enqueue` parameter to raise, emit, send, or stop work.
283
+ Planning stays synchronous: perform asynchronous work in an invocation.
565
284
 
566
- ## Statechart capabilities
285
+ `Machine.prepare(machine)` exposes an `inspection` stream for the live local
286
+ machine tree; subscribe before running `prepared.start` to observe startup. Distributed
287
+ placement, transport, routing, and identity belong to the explicit Cluster
288
+ adapter.
567
289
 
568
- `Machine.state` supports:
569
-
570
- - atomic states;
571
- - compound states with one active child;
572
- - parallel states with one active state in every region;
573
- - final states and typed outputs;
574
- - transient choice states;
575
- - shallow and deep history states.
290
+ ## Statechart capabilities
576
291
 
577
- Declare topology—including finality, output schemas, choices, and history—only
578
- in `states`. Handlers implement behavior and output computation without
579
- repeating structural metadata. Final children complete their parent, so
580
- `onDone` belongs on that compound or parallel parent.
292
+ The same root supports compound and parallel states, eventless `always`
293
+ transitions, ordered named choices, final states, `onDone` completion,
294
+ initial declarations, shallow and deep history, and retained snapshots. The topology
295
+ is captured directly from declarations; visualization and branch coverage do
296
+ not execute user resolvers or depend on TypeScript source extraction.
581
297
 
582
- Transition, entry, exit, choice, initial, and history callbacks are
583
- synchronous. Conditions use ordinary TypeScript control flow. Callbacks may
584
- select state and enqueue explicit `raise`, `emit`, `sendTo`, or `stop` commands;
585
- arbitrary asynchronous Effects do not run inside planning.
298
+ A compound root completes with its direct completed workflow's output unless
299
+ that child handles completion first. Parallel completion waits for all required
300
+ regions. An arbitrary final descendant does not finish every ancestor.
586
301
 
587
302
  ## Effects, Streams, timers, and child machines
588
303
 
589
- State-scoped work starts on entry and is interrupted on exit:
304
+ Register programs inside `make`, then invoke them by `src`:
590
305
 
591
306
  ```ts
592
- machine.handle({
307
+ const Search = Machine.make({
308
+ root: Root,
309
+ events: Events,
310
+ effects: {
311
+ load: (query: string) => searchItems(query),
312
+ refreshCache: Cache.refresh
313
+ },
314
+ streams: { updates: changes },
315
+ timers: { timeout: "5 seconds" },
316
+ logic: { worker: workerLogic },
317
+ children: { validation: ValidationChild }
318
+ }).handle({
319
+ initial: {
320
+ target: Machine.targets(Root).root.Idle
321
+ },
593
322
  states: {
323
+ Idle: {},
594
324
  Loading: {
595
- invoke: (from) =>
596
- from.effect("save-document", () => saveDocument)
597
- .onDone((to) => to.branch.Saved().resolve(({ output, target }) => target.from({ id: output.id })))
598
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ message: String(error) })))
325
+ invoke: {
326
+ src: "load",
327
+ input: ({ state }) => state.query,
328
+ onDone: { target: targets.root.Ready, data: ({ output }) => ({ items: output }) },
329
+ onFailure: { target: targets.root.Failed, data: ({ error }) => ({ message: error.message }) }
330
+ }
599
331
  },
600
- Waiting: {
601
- invoke: (from) =>
602
- from.timer("save-timeout", "3 seconds")
603
- .onDone((to) => to.branch.Failed().resolve(({ target }) => target.from({ message: "Timed out" })))
604
- }
605
- }
606
- })
607
- ```
608
-
609
- The state-local `from` selector starts an `effect`, `stream`, `timer`, reusable
610
- `logic`, or complete `child` statechart. The selected source determines which
611
- lifecycle methods the chain requires and which methods are available. For
612
- example, an Effect with non-`never` output and error channels must handle both;
613
- the completed chain is the value returned by the callback:
614
-
615
- ```ts
616
- machine.handle({
617
- states: {
618
- Loading: {
619
- invoke: (from) =>
620
- from.effect("load-document", ({ state }) => loadDocument(state.documentId))
621
- .onDone((to) => to.branch.Ready().resolve(({ output, target }) => target.from({ document: output })))
622
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ message: error.message })))
623
- }
624
- }
625
- })
626
- ```
627
-
628
- A Stream source remains independent of the parent event protocol. Each element
629
- is mapped by `onElement`, and the next element is not pulled until that parent
630
- macrostep commits:
631
-
632
- ```ts
633
- machine.handle({
634
- states: {
635
- Listening: {
636
- invoke: (from) =>
637
- from.stream("channel", () => channelMessages)
638
- .onElement((to) =>
639
- to.none.resolve(({ element }, enqueue) => {
640
- enqueue.raise(Events.MessageReceived({ message: element }))
641
- })
642
- )
643
- .onDone((to) => to.none)
644
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ error })))
645
- }
646
- }
647
- })
648
- ```
649
-
650
- `to.none` is the targetless transition value. Return it directly to keep the
651
- current configuration, or call `.resolve(...)` when the transition only needs
652
- to enqueue commands. A block resolver may omit its return because it is
653
- contextually typed to return `undefined`.
654
-
655
- Inside `.handle(...)`, `from` receives the owning machine's public input and
656
- declared parent protocol contextually. Source and lifecycle callbacks can send
657
- through `self` and `parent` while retaining the invoked Effect's output and
658
- error inference:
659
-
660
- ```ts
661
- const machine = Machine.make({
662
- events: Commands,
663
- internalEvents: InternalEvents,
664
- parent: Machine.parent(ParentEvents)
665
- // ...
666
- }).handle({
667
- states: {
668
- Saving: {
669
- invoke: (from) =>
670
- from.effect("notify-parent", () => saveDocument)
671
- .onDone((to) =>
672
- to.none.resolve(({ parent, self }, enqueue) => {
673
- enqueue.sendTo(self, Commands.Save())
674
- enqueue.sendTo(parent, ParentEvents.ChildFinished({ id: "job-1" }))
675
- })
676
- )
677
- .onFailure((to) => to.none)
678
- }
332
+ Ready: {},
333
+ Failed: {}
679
334
  }
680
335
  })
681
336
  ```
682
337
 
683
- Return an array of completed chains to compose multiple state-owned activities.
684
- The source computation itself, process logic, or `Machine.child(id, machine)`
685
- descriptor can be named and reused; the invocation chain stays local so its
686
- transitions retain the exact owning state and machine protocols.
687
-
688
- ```ts
689
- const refreshCache = Cache.refresh
690
-
691
- machine.handle({
692
- states: {
693
- Active: {
694
- invoke: (from) => [
695
- from.effect("refresh-cache", () => refreshCache).onDone((to) => to.none).onFailure((to) => to.none),
696
- from.timer("expire-session", "5 minutes").onDone((to) => to.branch.Expired())
697
- ]
698
- }
699
- }
700
- })
701
- ```
702
-
703
- `onDone` is required for a non-`never` output, and `onFailure` is required for a
704
- non-`never` typed error. Streams additionally require `onElement` when their
705
- element channel is non-`never` and always require `onDone`; logic and child
706
- chains optionally expose `onSnapshot`. A handled method disappears from the
707
- next builder step, so every reachable lifecycle channel is handled exactly
708
- once. Defects, interruption, and source-construction failures terminate the
709
- owning runtime. Effect sources are factories evaluated when their state is
710
- entered. Use an Effect containing `Effect.sleep(...)` for generic work, while
711
- `from.timer(...)` keeps timer intent explicit and makes static durations visible
712
- through activity inspection.
713
-
714
- ### Spawn dynamic child machines
715
-
716
- Use `from.child(...)` when a state owns a fixed child lifecycle. Use the
717
- `children` context inside an invoked Effect when the machine process owns an
718
- open set of children that must survive state changes:
719
-
720
- ```ts
721
- const Plant = Machine.childFamily(plantMachine)
722
-
723
- const central = Machine.make({
724
- events: Machine.eventsFromSchemas(ResourcesOffered, PlantBroken)
725
- // ...
726
- }).handle({
727
- states: {
728
- Commissioning: {
729
- invoke: (from) =>
730
- from.effect("commission-wave", ({ children, state }) =>
731
- Effect.forEach(
732
- state.plants,
733
- (input) => children.spawn(Plant(input.id), { input }),
734
- { discard: true }
735
- ))
736
- .onDone((to) => to.branch.Operating())
737
- .onFailure((to) => to.branch.CommissioningFailed())
738
- }
739
- }
740
- })
741
- ```
742
-
743
- `children.spawn` completes after initialization. The new child remains owned
744
- by the machine process after the commissioning Effect completes or its state
745
- exits. `children.sendTo` and `children.stop` address one active child from an
746
- Effect; transition resolvers use `enqueue.sendTo` and `enqueue.stop` with the
747
- same descriptor. Duplicate active ids fail with `ChildAlreadyExistsError` and
748
- do not replace the existing child. Earlier successful spawns remain active if
749
- a later spawn in the same wave fails.
750
-
751
- The child machine's declared `Machine.parent(...)` events must be accepted by
752
- the owner. This is checked at each spawn call even though ids and cardinality
753
- remain dynamic. `scope.spawn(child, { input })` provides the same descriptor
754
- form for lower-level process logic, where the process event protocol is known.
338
+ Effects and Streams are lazy values: pass them directly when they need no
339
+ input. Use `Effect.suspend` or `Stream.suspend` when construction itself must be
340
+ deferred. An input-taking source has exactly one required parameter and the
341
+ invocation must supply a typed `input` mapper. A direct value forbids `input`.
342
+ Zero-argument and optional-argument factories are rejected to keep this choice
343
+ explicit. Source names are unique across all five registries.
344
+
345
+ | Source | Required handlers | Optional handlers |
346
+ | -------------- | --------------------------------------------------------------------------------------------------- | ----------------- |
347
+ | Effect | `onDone` when success is not `never`; `onFailure` when error is not `never` | None |
348
+ | Stream | `onElement` when its element is not `never`; `onFailure` when error is not `never`; always `onDone` | None |
349
+ | Timer | `onDone` | None |
350
+ | Logic or child | Reachable `onDone` and `onFailure` | `onSnapshot` |
351
+
352
+ A `void` success still requires `onDone`. Unreachable channels are rejected.
353
+ Startup errors, defects, and interruption follow the existing runtime failure
354
+ and cancellation boundaries; a typed `onFailure` handles the source's declared
355
+ runtime error channel.
356
+
357
+ ```ts
358
+ const invocations = [
359
+ {
360
+ src: "updates",
361
+ onElement: {
362
+ none: true,
363
+ resolve: ({ element }, enqueue) => {
364
+ enqueue.raise(Events.Changed({ value: element }))
365
+ }
366
+ },
367
+ onDone: { none: true },
368
+ onFailure: { none: true }
369
+ },
370
+ { src: "timeout", onDone: { target: targets.root.Expired } },
371
+ { src: "worker", id: "worker", address: WorkerAddress, onSnapshot: { none: true } },
372
+ { src: "validation", input: ({ state }) => ({ query: state.query }), onDone: { none: true } }
373
+ ]
374
+ ```
375
+
376
+ Include each handler demanded by the concrete program's type. Use an explicit
377
+ `id` for simultaneous instances of one source; effect, stream, and timer IDs
378
+ default to `src`. Logic requires a lifecycle `id` and a typed `Machine.childAddress`.
379
+ A child uses its `Machine.child` descriptor's identity and protocol. All
380
+ invocations are owned by their state and cancelled when it exits.
381
+
382
+ Effect services flow through the used sources and lifecycle effects into the
383
+ machine's requirements. Unused registrations add no requirements. Supply them
384
+ with ordinary `Effect.provide` / `Effect.provideService`, or an Atom runtime
385
+ backed by a Layer. Context services provide implementation substitution and
386
+ scoped resources; there is no separate machine-specific dependency container.
387
+
388
+ ### Dynamic children
389
+
390
+ A registered `Machine.child` describes a fixed state-owned child. For an open
391
+ set of process-owned children, use `Machine.childFamily` with the `children`
392
+ capability supplied to a registered Effect through its input mapper.
393
+ `children.spawn` completes after child initialization; the child survives the
394
+ commissioning invocation and state. `children.sendTo` and `children.stop`
395
+ address it from Effects; resolvers use `enqueue.sendTo` and `enqueue.stop`.
396
+ Duplicate active IDs fail with `ChildAlreadyExistsError` and preserve the
397
+ existing child. Parent-protocol compatibility is checked at each spawn.
755
398
 
756
399
  ## Reactivity
757
400
 
@@ -902,8 +545,8 @@ import { MachineTest } from "@typeonce/effect-machine/testing"
902
545
 
903
546
  const trace = yield* MachineTest.run(Counter, {
904
547
  events: [
905
- { _tag: "Start" },
906
- { _tag: "Increment" }
548
+ { _tag: "Increment", by: 1 },
549
+ { _tag: "Increment", by: 2 }
907
550
  ]
908
551
  })
909
552
 
@@ -939,8 +582,9 @@ pnpm install --frozen-lockfile
939
582
  pnpm check
940
583
  ```
941
584
 
942
- Declarative first-class guards are not currently part of the API; use ordinary
943
- TypeScript conditions. Pull requests that change `src/` or `package.json` need
585
+ Use `guard: predicate` to decline before construction, or `declinable: true`
586
+ when a resolver can return `decline()`.
587
+ Pull requests that change `src/` or `package.json` need
944
588
  a changeset and the performance checks described in `AGENTS.md`.
945
589
 
946
590
  When equivalent Machine modules ship in Effect, this package is intended to