@typeonce/effect-machine 0.32.0 → 0.34.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 (108) hide show
  1. package/README.md +216 -635
  2. package/dist/Machine.d.ts +814 -545
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -8
  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 -1
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -45
  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 +5 -4
  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/invocation.d.ts +1 -1
  34. package/dist/internal/machine/invocation.d.ts.map +1 -1
  35. package/dist/internal/machine/invocation.js +1 -1
  36. package/dist/internal/machine/invocation.js.map +1 -1
  37. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  38. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  39. package/dist/internal/machine/machine.d.ts +13 -2
  40. package/dist/internal/machine/machine.d.ts.map +1 -1
  41. package/dist/internal/machine/machine.js +149 -280
  42. package/dist/internal/machine/machine.js.map +1 -1
  43. package/dist/internal/machine/planner.d.ts.map +1 -1
  44. package/dist/internal/machine/planner.js +12 -11
  45. package/dist/internal/machine/planner.js.map +1 -1
  46. package/dist/internal/machine/process.d.ts +8 -7
  47. package/dist/internal/machine/process.d.ts.map +1 -1
  48. package/dist/internal/machine/process.js +16 -12
  49. package/dist/internal/machine/process.js.map +1 -1
  50. package/dist/internal/machine/runtime.d.ts +2 -230
  51. package/dist/internal/machine/runtime.d.ts.map +1 -1
  52. package/dist/internal/machine/runtime.js +8 -1857
  53. package/dist/internal/machine/runtime.js.map +1 -1
  54. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  55. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  56. package/dist/internal/machine/runtimeCompiled.js +867 -0
  57. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  58. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  59. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  60. package/dist/internal/machine/runtimeGeneric.js +471 -0
  61. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  62. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  63. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeProtocol.js +561 -0
  65. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  66. package/dist/internal/machine/targetReference.d.ts +15 -0
  67. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  68. package/dist/internal/machine/targetReference.js +31 -0
  69. package/dist/internal/machine/targetReference.js.map +1 -0
  70. package/dist/internal/machine/topology.d.ts.map +1 -1
  71. package/dist/internal/machine/topology.js +2 -1
  72. package/dist/internal/machine/topology.js.map +1 -1
  73. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  74. package/dist/internal/testing/machine/finiteModel.js +38 -40
  75. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  76. package/dist/internal/testing/machine/probe.js +1 -1
  77. package/dist/internal/testing/machine/probe.js.map +1 -1
  78. package/dist/unstable/cluster/ClusterMachine.d.ts +5 -5
  79. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  80. package/dist/unstable/cluster/ClusterMachine.js +5 -17
  81. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  82. package/docs/agent-guide.md +66 -91
  83. package/docs/machine-review.md +19 -49
  84. package/docs/root-api.md +68 -23
  85. package/package.json +1 -1
  86. package/src/Machine.ts +1387 -2011
  87. package/src/internal/machine/childRegistry.ts +1 -1
  88. package/src/internal/machine/cluster.ts +7 -73
  89. package/src/internal/machine/clusterProtocol.ts +56 -0
  90. package/src/internal/machine/commandRuntime.ts +1 -1
  91. package/src/internal/machine/configuration.ts +53 -45
  92. package/src/internal/machine/declaration.ts +140 -0
  93. package/src/internal/machine/executionPlan.ts +6 -5
  94. package/src/internal/machine/implementation.ts +41 -0
  95. package/src/internal/machine/invocation.ts +3 -3
  96. package/src/internal/machine/invocationDefinition.ts +1 -1
  97. package/src/internal/machine/machine.ts +210 -389
  98. package/src/internal/machine/planner.ts +54 -35
  99. package/src/internal/machine/process.ts +40 -33
  100. package/src/internal/machine/runtime.ts +20 -3037
  101. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  102. package/src/internal/machine/runtimeGeneric.ts +799 -0
  103. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  104. package/src/internal/machine/targetReference.ts +40 -0
  105. package/src/internal/machine/topology.ts +2 -1
  106. package/src/internal/testing/machine/finiteModel.ts +42 -43
  107. package/src/internal/testing/machine/probe.ts +1 -1
  108. package/src/unstable/cluster/ClusterMachine.ts +9 -17
package/README.md CHANGED
@@ -42,25 +42,25 @@ 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
50
 
51
51
  const Root = Machine.state({ fields: { count: Schema.Number } })
52
+ const targets = Machine.targets(Root)
52
53
  const Events = Machine.events({ Increment: { by: Schema.Number } })
53
- const CounterDefinition = Machine.make({
54
+ const Counter = Machine.make({
54
55
  root: Root,
55
56
  events: Events,
56
57
  initial: (root) => root.from(() => ({ count: 0 }))
57
- })
58
- const Counter = CounterDefinition.handle({
58
+ }).handle({
59
59
  on: {
60
- Increment: (to) =>
61
- to.self.update.from(({ current, event }) => ({
62
- count: current.count + event.by
63
- }))
60
+ Increment: {
61
+ update: targets.root,
62
+ from: ({ root, event }) => ({ count: root.count + event.by })
63
+ }
64
64
  }
65
65
  })
66
66
 
@@ -70,687 +70,267 @@ const program = Effect.scoped(Effect.gen(function*() {
70
70
  }))
71
71
  ```
72
72
 
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.
73
+ Root data is shared state. `update: targets.root` replaces that value while
74
+ retaining the active child configuration and its running work. Ordinary
75
+ transitions target a descendant; the root itself is not a destination.
94
76
 
95
77
  ## Modeling workflow
96
78
 
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.
79
+ Put data on the lowest state that owns it. Use tagged schemas or `fields` for
80
+ state-owned values and `{}` for structural states. Prefer distinct states over
81
+ boolean flags that allow impossible combinations. Put shared behavior on the
82
+ lowest common ancestor, and reserve parallel states for independent modes.
156
83
 
157
- When sibling states share fields, remove the source discriminator and pass the
158
- remaining fields through the target schema:
159
-
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
- ```
84
+ `Machine.state` declares topology. `Machine.make` captures protocols, startup
85
+ input, sources, and named branch groups. `.handle` implements behavior in one
86
+ nested object and returns an executable machine. One definition can create
87
+ independent implementations by calling `.handle` more than once.
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
+ ### Construct state values
172
90
 
173
91
  ```ts
174
- const States = Machine.state({
175
- initial: "Form",
92
+ const Root = Machine.state({
93
+ initial: "Idle",
176
94
  states: {
177
- Form: {
178
- initial: "Editing",
179
- states: {
180
- Editing: {},
181
- Saving
182
- }
183
- }
95
+ Idle: {},
96
+ Loading: { fields: { query: Schema.String } },
97
+ Ready: { fields: { items: Schema.Array(Schema.String) } },
98
+ Failed: { fields: { message: Schema.String } }
184
99
  }
185
100
  })
101
+ const targets = Machine.targets(Root)
102
+ const Events = Machine.events({ Search: { query: Schema.String }, Reset: {} })
186
103
 
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())))
104
+ const Search = Machine.make({ root: Root, events: Events }).handle({
105
+ states: {
106
+ Idle: {
107
+ on: {
108
+ Search: {
109
+ target: targets.root.Loading,
110
+ from: ({ event }) => ({ query: event.query })
111
+ }
112
+ }
113
+ },
114
+ Loading: { on: { Reset: { target: targets.root.Idle } } }
115
+ }
192
116
  })
193
117
  ```
194
118
 
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.
119
+ `from` accepts the schema's make input, including defaults and transformations.
120
+ `decoded` accepts its decoded value, preserving class instances. The planner
121
+ validates both boundaries and reports `MachineSchemaDecodeError`. Omit construction
122
+ only when the selected builder supports empty default construction.
204
123
 
205
- Put data on the narrowest state where it is valid. If sibling phases share
206
- data, put it on their compound parent.
124
+ A callback receives the specific event and source-state types, plus `root`,
125
+ `containingState`, `ancestors`, and the appropriate machine references. A
126
+ transition callback also receives the current logical `snapshot`. There is no
127
+ unrestricted destination builder in the callback.
207
128
 
208
- ### Separate inputs, raised events, and emissions
129
+ ### Declare advanced and conditional transitions
209
130
 
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:
131
+ A resolver that chooses a branch, constructs nested children, or enqueues
132
+ commands uses a named group in `make`. The group captures every possible edge
133
+ before any resolver executes:
213
134
 
214
135
  ```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()
237
- })
238
- ```
239
-
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
- )
297
-
298
- const checkoutRef = yield * prepared.start
299
- ```
300
-
301
- For a handled input, the stream may expose values such as:
302
-
303
- ```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()
136
+ const machine = Machine.make({
137
+ root: Root,
138
+ events: Events,
139
+ branches: {
140
+ search: {
141
+ loading: { target: targets.root.Loading, title: "Query supplied" },
142
+ idle: { target: targets.root.Idle, title: "Empty query" }
143
+ }
144
+ }
350
145
  }).handle({
351
146
  states: {
352
- Working: {
147
+ Idle: {
353
148
  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
- })
149
+ Search: {
150
+ branches: "search",
151
+ resolve: ({ event, select }) =>
152
+ event.query.length > 0
153
+ ? select.loading.from({ query: event.query })
154
+ : select.idle.from()
155
+ }
359
156
  }
360
- },
361
- Done: {}
157
+ }
362
158
  }
363
159
  })
364
-
365
- const Child = Machine.child("worker", child)
366
- const ParentInputs = Machine.eventsFromSchemas(Start, ParentEvents)
367
160
  ```
368
161
 
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()` for resolver-free reentry or pass `{ reenter: true }`
415
- to `.resolve(...)` when the source must restart. With `to.none`, reentry
416
- restarts the source while retaining its configuration.
417
-
418
- Topology-only definition instructions are values: `to.none`, declared
419
- `.initial` and history selections, and `to.local.with`. Concrete state and
420
- choice destinations remain calls such as `to.local.Running()`. Runtime named
421
- branch builders remain callable, including `select.unchanged()`, because their
422
- result carries the selected branch evidence.
423
-
424
- ### Update an active scope value
425
-
426
- Use `to.local.update(...)` to replace the value owned by the nearest active
427
- compound scope without rebuilding its active child. Use
428
- `to.branch.<path>.update(...)` for a valued compound or parallel ancestor of the
429
- handler source:
162
+ Each selector is bound to its declared destination. Its constructor rejects a
163
+ payload belonging to another branch. A single-target group works the same way;
164
+ there is no second path declaration in the resolver. For a compound target,
165
+ `select.checkout.from(parentValues, child => child.Review.from(childValues))`
166
+ constructs the explicitly selected subtree. Parallel constructors require every
167
+ entered region. Required initializers and final output implementations remain
168
+ part of machine readiness checking.
430
169
 
431
- ```ts
432
- const handlers = {
433
- Increment: (to) => to.branch.root.session.update(({ current, owner }) => owner.from({ count: current.count + 1 }))
434
- }
435
- ```
170
+ Use `guard: context => boolean` to decline before construction or commands.
171
+ For a resolver that can decline, explicitly add `declinable: true`; only then may
172
+ it return `context.decline()`. `reenter: true` restarts the handler's source
173
+ where that operation supports reentry. A retained source-value update does not
174
+ restart its lifecycle.
436
175
 
437
- The update keeps the exact active descendants, their values, history records,
438
- completion outputs, and unrelated parallel regions. It runs no exit or entry
439
- actions and does not restart state-owned work. Eventless stabilization still
440
- runs, so an `always` transition can react to the new value.
176
+ ### Select destinations and retain owners
441
177
 
442
- The plain update method remains useful when topology does not change. It is
443
- also a static selection for a named branch:
178
+ All references come from the same root descriptor supplied to `make`:
444
179
 
445
- ```ts
446
- to.branches({
447
- changed: { target: to.local.update },
448
- unchanged: { target: to.none }
449
- }).resolve(({ select, event }) =>
450
- event.changed
451
- ? select.changed.from({ count: event.count })
452
- : select.unchanged()
453
- )
454
- ```
455
-
456
- ### Change topology and a retained owner together
180
+ | Declaration | Meaning |
181
+ | ----------------------------------------------------- | ------------------------------------------------------------------------- |
182
+ | `{ target: targets.root.Checkout.Review, from: ... }` | Enter a declared destination with its value. |
183
+ | `{ initial: targets.root.Checkout, from: ... }` | Enter the declared initial configuration of a compound or parallel state. |
184
+ | `{ history: targets.root.Checkout.recent }` | Restore a declared history state. |
185
+ | `{ update: targets.root.Checkout, from: ... }` | Replace a retained active owner's value. |
186
+ | `{ update: targets.root, from: ... }` | Replace root data and retain active descendants. |
187
+ | `{ none: true }` | Accept an event without changing the configuration. |
457
188
 
458
- When a transition enters another child and also replaces a valued ancestor
459
- that stays active, declare both operations on the same target:
189
+ An atomic transition can enter a destination and update one retained owner:
460
190
 
461
191
  ```ts
462
- const handlers = {
463
- CreatePlan: (to) =>
464
- to.local.SavingPlan()
465
- .updating(to.branch.Ready)
466
- .resolve(({ current, event, owner, target }) =>
467
- target.from({
468
- request: { _tag: "Create", input: event.input }
469
- }).update(
470
- owner.decoded(new Ready({ ...current, notice: null }))
471
- )
472
- )
192
+ Save: {
193
+ target: targets.root.Checkout.Saving,
194
+ update: targets.root.Checkout,
195
+ from: ({ event, ancestors }) => ({
196
+ target: { request: event.request },
197
+ update: { ...ancestors.Checkout, revision: event.revision }
198
+ })
473
199
  }
474
200
  ```
475
201
 
476
- `to.local.SavingPlan()` selects topology. `.updating(to.branch.Ready)` names
477
- the retained valued owner and makes its replacement mandatory: the resolver
478
- does not type-check unless destination construction finishes with
479
- `.update(...)`. `current` is that owner's decoded value from the
480
- pre-transition snapshot. `target` constructs the destination; `owner`
481
- constructs the complete replacement owner value.
482
-
483
- The topology change and owner replacement apply atomically in one microstep.
484
- The owner does not exit or reenter, its work is not restarted, and destination
485
- entry actions observe the new owner value. Eventless stabilization follows.
486
- Only one retained owner may be replaced by a combined target. A `full` target,
487
- or any target that exits the selected owner, does not expose `.updating`.
488
- Combined updates use a direct resolver in this release; named branches continue
489
- to support value-only updates.
490
-
491
- For a schema-less destination, construction remains explicit:
492
-
493
- ```ts
494
- to.local.Idle()
495
- .updating(to.branch.Ready)
496
- .resolve(({ current, output, owner, target }) =>
497
- target.from().update(
498
- owner.decoded(
499
- new Ready({
500
- ...current,
501
- day: output,
502
- notice: "Plan changed."
503
- })
504
- )
505
- )
506
- )
507
- ```
508
-
509
- Both values derive from the same pre-transition snapshot and are validated
510
- before lifecycle actions run. Competing transitions that write the same owner
511
- conflict; document order and hierarchy select one writer rather than applying
512
- last-write-wins behavior.
513
-
514
- The resolver must return `target.decoded(value)` or `target.from(input)`. It
515
- may return `decline()` only with `{ declinable: true }`. Pass `{ reenter: true }`
516
- on event or invocation transitions when the handler source should exit and
517
- enter again. Reentry applies to that source, not to the ancestor whose value
518
- changed.
202
+ The complete replacement values are validated before either change is applied.
203
+ Advanced construction declares both references in a branch and uses
204
+ `select.saved.from(destinationValues).update.from(ownerValues)`.
205
+ A retained owner must be active for that source and remain active through the
206
+ transition. A sibling region's value cannot be updated through this operation.
519
207
 
520
- The selector omits `update` for schema-less scopes, atomic and final states,
521
- inactive branches, parallel sibling regions, and choice resolvers. Updating a
522
- parallel sibling requires an event handled by that region.
208
+ The runtime transition API does not replace arbitrary complete root
209
+ configurations. `initialConfiguration` and history defaults retain complete
210
+ configuration construction for startup and restoration.
523
211
 
524
- Use `declinable: true` when a resolver may decide that its transition is not
525
- enabled. Only that resolver receives `decline()`, and its return type expands to
526
- accept the opaque declined result:
212
+ ### Protocols and ownership
527
213
 
528
- ```ts
529
- const handlers = {
530
- Submit: (to) =>
531
- to.local.Saving().resolve(
532
- ({ event, target, decline }) => accepts(event) ? target.from({ draft: event.draft }) : decline(),
533
- { declinable: true }
534
- )
535
- }
536
- ```
537
-
538
- Declining discards work enqueued by that resolver. Event and eventless dispatch
539
- continues with the next eligible ancestor; if no candidate accepts, no
540
- transition is selected. This differs from `target.none()`, which consumes the
541
- trigger and prevents an ancestor from handling it. `transitionDefinitions`
542
- reports each handler's `acceptance` as `"required"` or `"declinable"` while
543
- preserving the exact declared target branches. Choices and initial routing must
544
- remain total and cannot use declinable transitions. Completion and invocation
545
- outcomes have no ancestor candidate: declining one ignores that lifecycle
546
- occurrence and leaves the current configuration active.
547
-
548
- Use `Machine.can` when a caller needs to test a concrete event against a
549
- snapshot. The direct and machine-specialized forms have the same semantics:
214
+ `Machine.events` defines public messages. `Machine.internalEvents` adds
215
+ machine-local raised events; `Machine.emittedEvents` defines notifications.
216
+ Their `FromSchemas` counterparts accept existing tagged schemas. Public and
217
+ internal tags must be disjoint. Deferred event constructors are validated when
218
+ the runtime receives the event.
550
219
 
551
- ```ts
552
- const canSubmit = yield * Machine.can(machine, snapshot, Submit({ draft }))
553
-
554
- const canMachine = Machine.can(machine)
555
- const canCancel = yield * canMachine(snapshot, Cancel())
556
- ```
220
+ Declare `parent: Machine.parent(events)` for a required owner protocol, or
221
+ `Machine.optionalParent(events)` for a machine that may run independently.
222
+ Handlers receive typed `self` and, when declared, `parent` references. Resolvers
223
+ use their second `enqueue` parameter to raise, emit, send, or stop work.
224
+ Planning stays synchronous: perform asynchronous work in an invocation.
557
225
 
558
- `can` returns `true` when at least one required or non-declined handler accepts
559
- the event. Targetless transitions count as accepted. Invalid event input fails
560
- with `MachineSchemaDecodeError`; a valid unhandled event returns `false`.
561
- Declinable resolvers run to decide acceptance, but collected commands,
562
- emissions, and raised events are discarded. Required resolvers and transition
563
- lifecycle do not run.
226
+ `Machine.prepare(machine)` exposes an `inspection` stream for the live local
227
+ machine tree; subscribe before running `prepared.start` to observe startup. Distributed
228
+ placement, transport, routing, and identity belong to the explicit Cluster
229
+ adapter.
564
230
 
565
231
  ## Statechart capabilities
566
232
 
567
- `Machine.state` supports:
568
-
569
- - atomic states;
570
- - compound states with one active child;
571
- - parallel states with one active state in every region;
572
- - final states and typed outputs;
573
- - transient choice states;
574
- - shallow and deep history states.
575
-
576
- Declare topology—including finality, output schemas, choices, and history—only
577
- in `states`. Handlers implement behavior and output computation without
578
- repeating structural metadata. Final children complete their parent, so
579
- `onDone` belongs on that compound or parallel parent.
233
+ The same root supports compound and parallel states, eventless `always`
234
+ transitions, ordered named choices, final states, `onDone` completion,
235
+ initializers, shallow and deep history, and retained snapshots. The topology
236
+ is captured directly from declarations; visualization and branch coverage do
237
+ not execute user resolvers or depend on TypeScript source extraction.
580
238
 
581
- Transition, entry, exit, choice, initial, and history callbacks are
582
- synchronous. Conditions use ordinary TypeScript control flow. Callbacks may
583
- select state and enqueue explicit `raise`, `emit`, `sendTo`, or `stop` commands;
584
- arbitrary asynchronous Effects do not run inside planning.
239
+ A compound root completes with its direct completed workflow's output unless
240
+ that child handles completion first. Parallel completion waits for all required
241
+ regions. An arbitrary final descendant does not finish every ancestor.
585
242
 
586
243
  ## Effects, Streams, timers, and child machines
587
244
 
588
- State-scoped work starts on entry and is interrupted on exit:
589
-
590
- ```ts
591
- machine.handle({
592
- states: {
593
- Loading: {
594
- invoke: (from) =>
595
- from.effect("save-document", () => saveDocument)
596
- .onDone((to) => to.branch.Saved().resolve(({ output, target }) => target.from({ id: output.id })))
597
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ message: String(error) })))
598
- },
599
- Waiting: {
600
- invoke: (from) =>
601
- from.timer("save-timeout", "3 seconds")
602
- .onDone((to) => to.branch.Failed().resolve(({ target }) => target.from({ message: "Timed out" })))
603
- }
604
- }
605
- })
606
- ```
607
-
608
- The state-local `from` selector starts an `effect`, `stream`, `timer`, reusable
609
- `logic`, or complete `child` statechart. The selected source determines which
610
- lifecycle methods the chain requires and which methods are available. For
611
- example, an Effect with non-`never` output and error channels must handle both;
612
- the completed chain is the value returned by the callback:
613
-
614
- ```ts
615
- machine.handle({
616
- states: {
617
- Loading: {
618
- invoke: (from) =>
619
- from.effect("load-document", ({ state }) => loadDocument(state.documentId))
620
- .onDone((to) => to.branch.Ready().resolve(({ output, target }) => target.from({ document: output })))
621
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ message: error.message })))
622
- }
623
- }
624
- })
625
- ```
626
-
627
- A Stream source remains independent of the parent event protocol. Each element
628
- is mapped by `onElement`, and the next element is not pulled until that parent
629
- macrostep commits:
245
+ Register programs inside `make`, then invoke them by `src`:
630
246
 
631
247
  ```ts
632
- machine.handle({
633
- states: {
634
- Listening: {
635
- invoke: (from) =>
636
- from.stream("channel", () => channelMessages)
637
- .onElement((to) =>
638
- to.none.resolve(({ element }, enqueue) => {
639
- enqueue.raise(Events.MessageReceived({ message: element }))
640
- })
641
- )
642
- .onDone((to) => to.none)
643
- .onFailure((to) => to.branch.Failed().resolve(({ error, target }) => target.from({ error })))
644
- }
645
- }
646
- })
647
- ```
648
-
649
- `to.none` is the targetless transition value. Return it directly to keep the
650
- current configuration, or call `.resolve(...)` when the transition only needs
651
- to enqueue commands. A block resolver may omit its return because it is
652
- contextually typed to return `undefined`.
653
-
654
- Inside `.handle(...)`, `from` receives the owning machine's public input and
655
- declared parent protocol contextually. Source and lifecycle callbacks can send
656
- through `self` and `parent` while retaining the invoked Effect's output and
657
- error inference:
658
-
659
- ```ts
660
- const machine = Machine.make({
661
- events: Commands,
662
- internalEvents: InternalEvents,
663
- parent: Machine.parent(ParentEvents)
664
- // ...
665
- }).handle({
666
- states: {
667
- Saving: {
668
- invoke: (from) =>
669
- from.effect("notify-parent", () => saveDocument)
670
- .onDone((to) =>
671
- to.none.resolve(({ parent, self }, enqueue) => {
672
- enqueue.sendTo(self, Commands.Save())
673
- enqueue.sendTo(parent, ParentEvents.ChildFinished({ id: "job-1" }))
674
- })
675
- )
676
- .onFailure((to) => to.none)
677
- }
678
- }
679
- })
680
- ```
681
-
682
- Return an array of completed chains to compose multiple state-owned activities.
683
- The source computation itself, process logic, or `Machine.child(id, machine)`
684
- descriptor can be named and reused; the invocation chain stays local so its
685
- transitions retain the exact owning state and machine protocols.
686
-
687
- ```ts
688
- const refreshCache = Cache.refresh
689
-
690
- machine.handle({
691
- states: {
692
- Active: {
693
- invoke: (from) => [
694
- from.effect("refresh-cache", () => refreshCache).onDone((to) => to.none).onFailure((to) => to.none),
695
- from.timer("expire-session", "5 minutes").onDone((to) => to.branch.Expired())
696
- ]
697
- }
698
- }
699
- })
700
- ```
701
-
702
- `onDone` is required for a non-`never` output, and `onFailure` is required for a
703
- non-`never` typed error. Streams additionally require `onElement` when their
704
- element channel is non-`never` and always require `onDone`; logic and child
705
- chains optionally expose `onSnapshot`. A handled method disappears from the
706
- next builder step, so every reachable lifecycle channel is handled exactly
707
- once. Defects, interruption, and source-construction failures terminate the
708
- owning runtime. Effect sources are factories evaluated when their state is
709
- entered. Use an Effect containing `Effect.sleep(...)` for generic work, while
710
- `from.timer(...)` keeps timer intent explicit and makes static durations visible
711
- through activity inspection.
712
-
713
- ### Spawn dynamic child machines
714
-
715
- Use `from.child(...)` when a state owns a fixed child lifecycle. Use the
716
- `children` context inside an invoked Effect when the machine process owns an
717
- open set of children that must survive state changes:
718
-
719
- ```ts
720
- const Plant = Machine.childFamily(plantMachine)
721
-
722
- const central = Machine.make({
723
- events: Machine.eventsFromSchemas(ResourcesOffered, PlantBroken)
724
- // ...
248
+ const Search = Machine.make({
249
+ root: Root,
250
+ events: Events,
251
+ effects: {
252
+ load: (query: string) => searchItems(query),
253
+ refreshCache: Cache.refresh
254
+ },
255
+ streams: { updates: changes },
256
+ timers: { timeout: "5 seconds" },
257
+ logic: { worker: workerLogic },
258
+ children: { validation: ValidationChild }
725
259
  }).handle({
726
260
  states: {
727
- Commissioning: {
728
- invoke: (from) =>
729
- from.effect("commission-wave", ({ children, state }) =>
730
- Effect.forEach(
731
- state.plants,
732
- (input) => children.spawn(Plant(input.id), { input }),
733
- { discard: true }
734
- ))
735
- .onDone((to) => to.branch.Operating())
736
- .onFailure((to) => to.branch.CommissioningFailed())
261
+ Loading: {
262
+ invoke: {
263
+ src: "load",
264
+ input: ({ state }) => state.query,
265
+ onDone: { target: targets.root.Ready, from: ({ output }) => ({ items: output }) },
266
+ onFailure: { target: targets.root.Failed, from: ({ error }) => ({ message: error.message }) }
267
+ }
737
268
  }
738
269
  }
739
270
  })
740
271
  ```
741
272
 
742
- `children.spawn` completes after initialization. The new child remains owned
743
- by the machine process after the commissioning Effect completes or its state
744
- exits. `children.sendTo` and `children.stop` address one active child from an
745
- Effect; transition resolvers use `enqueue.sendTo` and `enqueue.stop` with the
746
- same descriptor. Duplicate active ids fail with `ChildAlreadyExistsError` and
747
- do not replace the existing child. Earlier successful spawns remain active if
748
- a later spawn in the same wave fails.
749
-
750
- The child machine's declared `Machine.parent(...)` events must be accepted by
751
- the owner. This is checked at each spawn call even though ids and cardinality
752
- remain dynamic. `scope.spawn(child, { input })` provides the same descriptor
753
- form for lower-level process logic, where the process event protocol is known.
273
+ Effects and Streams are lazy values: pass them directly when they need no
274
+ input. Use `Effect.suspend` or `Stream.suspend` when construction itself must be
275
+ deferred. An input-taking source has exactly one required parameter and the
276
+ invocation must supply a typed `input` mapper. A direct value forbids `input`.
277
+ Zero-argument and optional-argument factories are rejected to keep this choice
278
+ explicit. Source names are unique across all five registries.
279
+
280
+ | Source | Required handlers | Optional handlers |
281
+ | -------------- | --------------------------------------------------------------------------------------------------- | ----------------- |
282
+ | Effect | `onDone` when success is not `never`; `onFailure` when error is not `never` | None |
283
+ | Stream | `onElement` when its element is not `never`; `onFailure` when error is not `never`; always `onDone` | None |
284
+ | Timer | `onDone` | None |
285
+ | Logic or child | Reachable `onDone` and `onFailure` | `onSnapshot` |
286
+
287
+ A `void` success still requires `onDone`. Unreachable channels are rejected.
288
+ Startup errors, defects, and interruption follow the existing runtime failure
289
+ and cancellation boundaries; a typed `onFailure` handles the source's declared
290
+ runtime error channel.
291
+
292
+ ```ts
293
+ invoke: ;
294
+ ;[
295
+ {
296
+ src: "updates",
297
+ onElement: {
298
+ none: true,
299
+ resolve: ({ element }, enqueue) => {
300
+ enqueue.raise(Events.Changed({ value: element }))
301
+ }
302
+ },
303
+ onDone: { none: true },
304
+ onFailure: { none: true }
305
+ },
306
+ { src: "timeout", onDone: { target: targets.root.Expired } },
307
+ { src: "worker", id: "worker", address: WorkerAddress, onSnapshot: { none: true } },
308
+ { src: "validation", input: ({ state }) => ({ query: state.query }), onDone: { none: true } }
309
+ ]
310
+ ```
311
+
312
+ Include each handler demanded by the concrete program's type. Use an explicit
313
+ `id` for simultaneous instances of one source; effect, stream, and timer IDs
314
+ default to `src`. Logic requires a lifecycle `id` and a typed `Machine.childAddress`.
315
+ A child uses its `Machine.child` descriptor's identity and protocol. All
316
+ invocations are owned by their state and cancelled when it exits.
317
+
318
+ Effect services flow through the used sources and lifecycle effects into the
319
+ machine's requirements. Unused registrations add no requirements. Supply them
320
+ with ordinary `Effect.provide` / `Effect.provideService`, or an Atom runtime
321
+ backed by a Layer. Context services provide implementation substitution and
322
+ scoped resources; there is no separate machine-specific dependency container.
323
+
324
+ ### Dynamic children
325
+
326
+ A registered `Machine.child` describes a fixed state-owned child. For an open
327
+ set of process-owned children, use `Machine.childFamily` with the `children`
328
+ capability supplied to a registered Effect through its input mapper.
329
+ `children.spawn` completes after child initialization; the child survives the
330
+ commissioning invocation and state. `children.sendTo` and `children.stop`
331
+ address it from Effects; resolvers use `enqueue.sendTo` and `enqueue.stop`.
332
+ Duplicate active IDs fail with `ChildAlreadyExistsError` and preserve the
333
+ existing child. Parent-protocol compatibility is checked at each spawn.
754
334
 
755
335
  ## Reactivity
756
336
 
@@ -901,8 +481,8 @@ import { MachineTest } from "@typeonce/effect-machine/testing"
901
481
 
902
482
  const trace = yield* MachineTest.run(Counter, {
903
483
  events: [
904
- { _tag: "Start" },
905
- { _tag: "Increment" }
484
+ { _tag: "Increment", by: 1 },
485
+ { _tag: "Increment", by: 2 }
906
486
  ]
907
487
  })
908
488
 
@@ -938,8 +518,9 @@ pnpm install --frozen-lockfile
938
518
  pnpm check
939
519
  ```
940
520
 
941
- Declarative first-class guards are not currently part of the API; use ordinary
942
- TypeScript conditions. Pull requests that change `src/` or `package.json` need
521
+ Use `guard: predicate` to decline before construction, or `declinable: true`
522
+ when a resolver can return `decline()`.
523
+ Pull requests that change `src/` or `package.json` need
943
524
  a changeset and the performance checks described in `AGENTS.md`.
944
525
 
945
526
  When equivalent Machine modules ship in Effect, this package is intended to