@typeonce/effect-machine 0.35.0 → 0.37.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 (72) hide show
  1. package/README.md +45 -7
  2. package/dist/Machine.d.ts +143 -136
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +25 -0
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/command.d.ts +0 -1
  7. package/dist/internal/machine/command.d.ts.map +1 -1
  8. package/dist/internal/machine/command.js +0 -14
  9. package/dist/internal/machine/command.js.map +1 -1
  10. package/dist/internal/machine/configuration.d.ts.map +1 -1
  11. package/dist/internal/machine/configuration.js +15 -2
  12. package/dist/internal/machine/configuration.js.map +1 -1
  13. package/dist/internal/machine/construction.d.ts +9 -0
  14. package/dist/internal/machine/construction.d.ts.map +1 -0
  15. package/dist/internal/machine/construction.js +132 -0
  16. package/dist/internal/machine/construction.js.map +1 -0
  17. package/dist/internal/machine/declaration.d.ts +1 -0
  18. package/dist/internal/machine/declaration.d.ts.map +1 -1
  19. package/dist/internal/machine/declaration.js +4 -8
  20. package/dist/internal/machine/declaration.js.map +1 -1
  21. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  22. package/dist/internal/machine/executionPlan.js +13 -9
  23. package/dist/internal/machine/executionPlan.js.map +1 -1
  24. package/dist/internal/machine/implementation.d.ts +2 -3
  25. package/dist/internal/machine/implementation.d.ts.map +1 -1
  26. package/dist/internal/machine/implementation.js.map +1 -1
  27. package/dist/internal/machine/invocation.d.ts +1 -0
  28. package/dist/internal/machine/invocation.d.ts.map +1 -1
  29. package/dist/internal/machine/invocation.js +26 -3
  30. package/dist/internal/machine/invocation.js.map +1 -1
  31. package/dist/internal/machine/invocationDefinition.d.ts +3 -1
  32. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  33. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  34. package/dist/internal/machine/machine.d.ts +6 -0
  35. package/dist/internal/machine/machine.d.ts.map +1 -1
  36. package/dist/internal/machine/machine.js +70 -168
  37. package/dist/internal/machine/machine.js.map +1 -1
  38. package/dist/internal/machine/observation.d.ts +3 -0
  39. package/dist/internal/machine/observation.d.ts.map +1 -0
  40. package/dist/internal/machine/observation.js +28 -0
  41. package/dist/internal/machine/observation.js.map +1 -0
  42. package/dist/internal/machine/planner.d.ts.map +1 -1
  43. package/dist/internal/machine/planner.js +63 -17
  44. package/dist/internal/machine/planner.js.map +1 -1
  45. package/dist/internal/machine/topology.d.ts +6 -0
  46. package/dist/internal/machine/topology.d.ts.map +1 -1
  47. package/dist/internal/machine/topology.js.map +1 -1
  48. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  49. package/dist/internal/testing/machine/finiteModel.js +36 -76
  50. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  51. package/docs/agent-guide.md +57 -34
  52. package/docs/root-api.md +143 -190
  53. package/package.json +1 -1
  54. package/src/Machine.ts +223 -144
  55. package/src/internal/machine/command.ts +0 -16
  56. package/src/internal/machine/configuration.ts +13 -10
  57. package/src/internal/machine/construction.ts +147 -0
  58. package/src/internal/machine/declaration.ts +5 -7
  59. package/src/internal/machine/executionPlan.ts +13 -9
  60. package/src/internal/machine/implementation.ts +2 -3
  61. package/src/internal/machine/invocation.ts +34 -3
  62. package/src/internal/machine/invocationDefinition.ts +1 -0
  63. package/src/internal/machine/machine.ts +89 -223
  64. package/src/internal/machine/observation.ts +39 -0
  65. package/src/internal/machine/planner.ts +69 -18
  66. package/src/internal/machine/topology.ts +4 -0
  67. package/src/internal/testing/machine/finiteModel.ts +44 -122
  68. package/dist/internal/machine/targetBuilder.d.ts +0 -16
  69. package/dist/internal/machine/targetBuilder.d.ts.map +0 -1
  70. package/dist/internal/machine/targetBuilder.js +0 -333
  71. package/dist/internal/machine/targetBuilder.js.map +0 -1
  72. package/src/internal/machine/targetBuilder.ts +0 -525
@@ -22,7 +22,7 @@ const CounterState = Schema.TaggedUnion({
22
22
  Running: { count: Schema.Number }
23
23
  })
24
24
 
25
- export const CounterStates = Machine.state({ initial: "Idle", states: {
25
+ export const CounterStates = Machine.state({ states: {
26
26
  Idle: {},
27
27
  Running: CounterState.cases.Running
28
28
  } })
@@ -41,16 +41,15 @@ export const CounterMachine = Machine.make({
41
41
  id: "Counter",
42
42
  root: CounterStates,
43
43
  events: CounterEvents,
44
- initialConfiguration: root => root.resolve(({ target }) => target.from(to => to.Idle.from()))
45
- }).handle({ states: {
44
+ }).handle({ initial: { target: targets.root.Idle }, states: {
46
45
  Idle: {
47
46
  on: {
48
- Start: { target: targets.root.Running, from: () => ({ count: 0 }) }
47
+ Start: { target: targets.root.Running, data: () => ({ count: 0 }) }
49
48
  }
50
49
  },
51
50
  Running: {
52
51
  on: {
53
- Increment: { update: targets.root.Running, from: ({ state }) => ({ count: state.count + 1 }) },
52
+ Increment: { update: targets.root.Running, data: ({ state }) => ({ count: state.count + 1 }) },
54
53
  Stop: { target: targets.root.Idle }
55
54
  }
56
55
  }
@@ -62,19 +61,18 @@ Each step has one job:
62
61
  - `Machine.state` declares the root, its child topology, and state-owned data.
63
62
  - `Machine.events` declares the public messages the machine accepts and returns
64
63
  typed event constructors.
65
- - `Machine.make` joins the state tree, event protocol, input, and initial state.
66
- - `.handle` implements the behavior of every active state and returns the
64
+ - `Machine.make` joins the state tree, event protocol, input, and reusable sources.
65
+ - `.handle` declares initial children and implements the behavior of every active state and returns the
67
66
  machine to export.
68
67
 
69
68
  Chain `.handle` from `Machine.make`. Do not store the intermediate definition
70
69
  when the module exports one machine implementation.
71
70
 
72
- State builders construct the next snapshot. Use `.from(...)` for schema make
73
- input; defaults, transformations, and refinements run while the machine plans
74
- the transition. Use `.decoded(...)` only for an existing `Schema.Type`. It is
75
- validated against the type side without rerunning encoded transformations.
76
- Valued state builders are not callable, so the construction mode is always
77
- visible. Schema-less state construction uses `.from()`.
71
+ Use `data` for schema make input. Constructor defaults and validation run while
72
+ planning. Use `{ decoded: true, data }` for an existing schema Type; validation
73
+ still applies. Named selectors take the same object format, with nested children
74
+ under `states`. Structural states omit data. See [Root API](./root-api.md) for
75
+ startup input, root targets, subtree construction, and history fallbacks.
78
76
 
79
77
  The examples below show one modeling decision at a time. They omit unchanged
80
78
  state and event declarations already shown above.
@@ -108,7 +106,7 @@ const RequestState = Schema.TaggedUnion({
108
106
  Failed: { message: Schema.String }
109
107
  })
110
108
 
111
- const RequestStates = Machine.state({ initial: "Idle", states: {
109
+ const RequestStates = Machine.state({ states: {
112
110
  Idle: {},
113
111
  Loading: {},
114
112
  Ready: RequestState.cases.Ready,
@@ -141,12 +139,11 @@ const DocumentState = Schema.TaggedUnion({
141
139
  }
142
140
  })
143
141
 
144
- const DocumentStates = Machine.state({ initial: "Closed", states: {
142
+ const DocumentStates = Machine.state({ states: {
145
143
  Closed: {},
146
144
  Open: {
147
145
  // Editing, Saving, and SaveFailed all need the document and draft.
148
146
  schema: DocumentState.cases.Open,
149
- initial: "Editing",
150
147
  states: {
151
148
  Editing: {},
152
149
  Saving: {},
@@ -177,9 +174,10 @@ const documentTargets = Machine.targets(DocumentStates)
177
174
  const DocumentMachine = Machine.make({
178
175
  root: DocumentStates,
179
176
  events: DocumentEvents
180
- }).handle({ states: {
177
+ }).handle({ initial: { target: documentTargets.root.Closed }, states: {
181
178
  Closed: {},
182
179
  Open: {
180
+ initial: { target: documentTargets.root.Open.Editing },
183
181
  on: {
184
182
  // All Open children close the document in the same way.
185
183
  Close: { target: documentTargets.root.Closed }
@@ -245,19 +243,17 @@ child in every region. A parallel model therefore accepts the full product of
245
243
  those regions.
246
244
 
247
245
  ```ts
248
- const ScreenStates = Machine.state({ initial: "Screen", states: {
246
+ const ScreenStates = Machine.state({ states: {
249
247
  Screen: {
250
248
  type: "parallel",
251
249
  states: {
252
250
  connection: {
253
- initial: "Online",
254
251
  states: {
255
252
  Online: {},
256
253
  Offline: {}
257
254
  }
258
255
  },
259
256
  panel: {
260
- initial: "Closed",
261
257
  states: {
262
258
  Closed: {},
263
259
  Open: {}
@@ -266,6 +262,15 @@ const ScreenStates = Machine.state({ initial: "Screen", states: {
266
262
  }
267
263
  }
268
264
  } })
265
+ const screenTargets = Machine.targets(ScreenStates)
266
+ const ScreenMachine = Machine.make({ root: ScreenStates, events: Machine.events({}) }).handle({
267
+ initial: { target: screenTargets.root.Screen },
268
+ states: { Screen: { states: {
269
+ connection: { initial: { target: screenTargets.root.Screen.connection.Online } },
270
+ panel: { initial: { target: screenTargets.root.Screen.panel.Closed } }
271
+ } } }
272
+ })
273
+
269
274
  ```
270
275
 
271
276
  This model permits all four combinations: online with a closed panel, online
@@ -288,7 +293,7 @@ const LoadState = Schema.TaggedUnion({
288
293
  Failed: { message: Schema.String }
289
294
  })
290
295
 
291
- const LoadStates = Machine.state({ initial: "Idle", states: {
296
+ const LoadStates = Machine.state({ states: {
292
297
  Idle: {},
293
298
  Loading: LoadState.cases.Loading,
294
299
  Ready: LoadState.cases.Ready,
@@ -300,15 +305,14 @@ const LoadMachine = Machine.make({
300
305
  root: LoadStates,
301
306
  effects: { loadDocument },
302
307
  events: Machine.eventsFromSchemas(),
303
- initialConfiguration: root => root.resolve(({ target }) => target.from(to => to.Idle.from()))
304
- }).handle({ states: {
308
+ }).handle({ initial: { target: loadTargets.root.Idle }, states: {
305
309
  Idle: {},
306
310
  Loading: {
307
311
  invoke: {
308
312
  src: "loadDocument",
309
313
  input: ({ state }) => state.documentId,
310
- onDone: { target: loadTargets.root.Ready, from: ({ output }) => ({ content: output }) },
311
- onFailure: { target: loadTargets.root.Failed, from: ({ error }) => ({ message: String(error) }) }
314
+ onDone: { target: loadTargets.root.Ready, data: ({ output }) => ({ content: output }) },
315
+ onFailure: { target: loadTargets.root.Failed, data: ({ error }) => ({ message: String(error) }) }
312
316
  }
313
317
  },
314
318
  Ready: {},
@@ -334,8 +338,8 @@ Loading: {
334
338
  {
335
339
  src: "loadDocument",
336
340
  input: ({ state }) => state.documentId,
337
- onDone: { target: loadTargets.root.Ready, from: ({ output }) => ({ content: output }) },
338
- onFailure: { target: loadTargets.root.Failed, from: ({ error }) => ({ message: String(error) }) }
341
+ onDone: { target: loadTargets.root.Ready, data: ({ output }) => ({ content: output }) },
342
+ onFailure: { target: loadTargets.root.Failed, data: ({ error }) => ({ message: String(error) }) }
339
343
  },
340
344
  { src: "loadTimeout", onDone: { target: loadTargets.root.Idle } }
341
345
  ]
@@ -387,14 +391,14 @@ const ReviewMachine = Machine.make({
387
391
  rejected: { target: reviewTargets.root.Rejected }
388
392
  }
389
393
  }
390
- }).handle({ states: {
394
+ }).handle({ initial: { target: reviewTargets.root.Pending }, states: {
391
395
  Pending: {
392
396
  on: {
393
397
  Evaluate: {
394
398
  branches: "evaluate",
395
399
  resolve: ({ event, select }) => event.score >= 80
396
- ? select.accepted.from()
397
- : select.rejected.from()
400
+ ? select.accepted()
401
+ : select.rejected()
398
402
  }
399
403
  }
400
404
  },
@@ -414,7 +418,7 @@ descendants and running work:
414
418
  ```ts
415
419
  Changed: {
416
420
  update: targets.root.Document,
417
- from: ({ ancestors }) => ({
421
+ data: ({ ancestors }) => ({
418
422
  ...ancestors.Document,
419
423
  revision: ancestors.Document.revision + 1
420
424
  })
@@ -423,12 +427,11 @@ Changed: {
423
427
 
424
428
  Choose a valued source or retained ancestor explicitly. To change a parallel
425
429
  sibling, send an event handled by that sibling. Combine a destination and one
426
- retained owner update with `{ target, update, from }`; the callback returns
430
+ retained owner update with `{ target, update, data }`; the callback returns
427
431
  `{ target: destinationInput, update: completeOwnerInput }`. Both values are
428
432
  validated atomically, and destination entry sees the new owner value. A named
429
433
  branch can declare the same pair when a resolver needs commands or nested
430
- construction. Its constructor requires `.update.from(...)` or
431
- `.update.decoded(...)` before the selection can be returned.
434
+ construction. Its selector requires `update: { data: ownerValue }` in the construction object.
432
435
 
433
436
  ## Test paths and invariants
434
437
 
@@ -471,3 +474,23 @@ const testProgram = Effect.gen(function*() {
471
474
  Use pure planner traces for state and transition rules. Start a live machine
472
475
  and use `MachineTest.probe` when a test depends on timers, invoked work, raised
473
476
  events, or runtime scheduling.
477
+
478
+ ## Choose observation deliberately
479
+
480
+ Use atom selectors to render state, invocation outcomes to express workflow
481
+ behavior, `ref.join` to await final output, and `ref.changes` for ongoing
482
+ observation. Reach for `Machine.waitFor(ref, predicate)` only when an external
483
+ Effect or test must wait for a specific current or subsequent snapshot, such as
484
+ a long-lived connection becoming ready. Compose `Effect.timeout` when needed.
485
+
486
+ Do not use `send` followed by `waitFor` as an acknowledgement protocol. The current
487
+ snapshot might already match, and a match does not identify which event caused
488
+ it. Keep workflow steps in the machine. A matching terminal snapshot succeeds;
489
+ an unmatched error preserves its Cause, stopping fails with `StoppedError`, and
490
+ completion without a match fails with `Cause.NoSuchElementError`.
491
+
492
+ Invoked Effects, Streams, and timers already receive a `Machine.invoke` Effect
493
+ span with machine, state, source, and invocation identity. Use ordinary Effect
494
+ tracing configuration and application spans such as `Effect.fn("Payments.charge")`.
495
+ Do not add manual spans around every transition or introduce a second exporter.
496
+ Sender trace context is not automatically carried through machine mailboxes.
package/docs/root-api.md CHANGED
@@ -1,259 +1,212 @@
1
1
  # Root machine API
2
2
 
3
- A machine is one explicit root state. The root can own data, child topology,
4
- both, or neither. There is no separate global context store.
3
+ A machine has one root state. It can own data, child topology, both, or neither.
4
+ `Machine.state` declares that structure; `Machine.make` declares protocols and
5
+ reusable sources; `.handle` supplies initialization and behavior.
5
6
 
6
- ## Events and transitions only
7
+ ## Startup input and state data
7
8
 
8
9
  ```ts
9
10
  import { Machine } from "@typeonce/effect-machine"
10
11
  import { Schema } from "effect"
11
12
 
12
- const Events = Machine.events({ Open: {}, Close: {} })
13
13
  const Root = Machine.state({
14
- initial: "Closed",
15
- states: { Closed: {}, Open: {} }
16
- })
17
- const targets = Machine.targets(Root)
18
- const Door = Machine.make({ root: Root, events: Events }).handle({
19
- states: {
20
- Closed: { on: { Open: { target: targets.root.Open } } },
21
- Open: { on: { Close: { target: targets.root.Closed } } }
22
- }
23
- })
24
- ```
25
-
26
- The root declares the default child once. No startup target, empty schema, or
27
- resolver is needed. Structural nodes have `value: undefined` in snapshots.
28
-
29
- ## Root data and child data
30
-
31
- ```ts
32
- const Root = Machine.state({
33
- fields: { title: Schema.String },
34
- initial: "Editing",
14
+ fields: { locale: Schema.String },
35
15
  states: {
36
- Editing: { fields: { draft: Schema.String } },
37
- Saving: {}
16
+ Loading: { fields: { documentId: Schema.String } },
17
+ Ready: {}
38
18
  }
39
19
  })
40
- const Events = Machine.events({ Rename: { title: Schema.String }, Save: {} })
41
20
  const targets = Machine.targets(Root)
42
- const Editor = Machine.make({
21
+ const Events = Machine.events({
22
+ Loaded: {},
23
+ Reload: { locale: Schema.String, documentId: Schema.String }
24
+ })
25
+ const Document = Machine.make({
43
26
  root: Root,
44
27
  events: Events,
45
- initial: (root) => root.from(() => ({ title: "Untitled" }))
28
+ input: Schema.Struct({ locale: Schema.String, documentId: Schema.String })
46
29
  }).handle({
47
- initialize: ({ builder, state }) => builder.from({ draft: state.title }),
30
+ root: ({ input }) => ({ locale: input.locale }),
31
+ initial: {
32
+ target: targets.root.Loading,
33
+ data: ({ input }) => ({ documentId: input.documentId })
34
+ },
48
35
  on: {
49
- Rename: { update: targets.root, from: ({ event }) => ({ title: event.title }) }
36
+ Reload: {
37
+ target: targets.root,
38
+ input: ({ event }) => ({ locale: event.locale, documentId: event.documentId }),
39
+ reenter: true
40
+ }
50
41
  },
51
42
  states: {
52
- Editing: { on: { Save: { target: targets.root.Saving } } }
43
+ Loading: { on: { Loaded: { target: targets.root.Ready } } }
53
44
  }
54
45
  })
55
46
  ```
56
47
 
57
- `initialize` constructs the declared child configuration. Required values must
58
- be supplied before the machine becomes executable. Values whose schema make
59
- input is optional can use their schema defaults. A parallel owner's initializer
60
- constructs every required region through the typed builder.
61
-
62
- The complete snapshot always includes the root:
63
-
64
- ```ts
65
- // While Editing is active:
66
- {
67
- path: "",
68
- value: { _tag: "", title: "Untitled" },
69
- state: {
70
- path: "Editing",
71
- value: { _tag: "Editing", draft: "Untitled" }
72
- }
73
- }
74
- ```
75
-
76
- Root handlers remain active across child transitions. Child handlers receive
77
- their own state, typed ancestors, `root`, and the complete snapshot.
78
- `update: targets.root` addresses root data from a child. An explicit descendant
79
- reference addresses a valued handler owner or retained ancestor.
80
- Both replace the entire value; omitted fields are not silently retained.
81
- Updates preserve the active topology and do not restart scoped work.
82
-
83
- Simultaneous transitions retain conflict checking. Two parallel handlers cannot
84
- silently overwrite the same owner. Use `{ target, update }` to combine a selected destination and a retained
85
- owner's value in one atomic transition.
48
+ Start with `Machine.start(Document, { locale: "en", documentId: "intro" })`.
49
+ Root construction runs before its initial child construction. Both receive the
50
+ same validated input. `documentId` belongs only to Loading; it need not be stored
51
+ in root data. Input is not retained as a reset value on the machine or snapshot.
86
52
 
87
- ## Schemas and reusable descriptors
53
+ Only the root's initial callbacks receive machine input. Nested initial callbacks
54
+ receive their owning state, ancestors, root, and lifecycle event. Pass any needed
55
+ values through the nested state's data. Input is not an entry/exit capability.
88
56
 
89
- Use `fields` for local data or `schema` for an existing tagged schema. They are
90
- mutually exclusive. A schema preserves class identity, refinements, defaults,
91
- and transformations; its tag is independent of its mount path.
57
+ For a parallel root, every required region constructor receives input:
92
58
 
93
59
  ```ts
94
- class Ready extends Schema.TaggedClass<Ready>("Ready")("Ready", {
95
- name: Schema.String
96
- }) {}
97
-
98
- const Form = Machine.state({
99
- initial: "Idle",
100
- states: { Idle: {}, Ready: { schema: Ready } }
101
- })
102
- const Root = Machine.state({
103
- type: "parallel",
104
- states: { First: Form, Second: Form }
105
- })
60
+ initial: {
61
+ Documents: ({ input }) => ({ folder: input.folder }),
62
+ Connection: ({ input }) => ({ endpoint: input.endpoint })
63
+ }
106
64
  ```
107
65
 
108
- Each mount has its own path and lifecycle. Descriptors capture their definition
109
- without retaining caller-owned mutable topology containers. `Machine.make`
110
- accepts the complete descriptor as `root`; callers do not extract its internals.
111
-
112
- `Machine.events({ Save: { title: Schema.String } })` creates a deferred
113
- `Events.Save({ title })` constructor. The machine validates it when processing
114
- the event. To reuse tagged classes or a tagged union, use
115
- `Machine.eventsFromSchemas(...)`. Internal and emitted protocols have distinct
116
- constructors with the same fields/import distinction. Public sends cannot send
117
- internal events, and emissions do not become machine input events implicitly.
66
+ Structural regions require no data. Schema constructor defaults can supply
67
+ optional region data. Compound handlers declare one direct initial child with
68
+ `initial: { target, data }`; each compound has its own initial declaration.
69
+ There is no `initialConfiguration` or initializer in `make`.
118
70
 
119
- ## Default initialization and explicit configuration
71
+ ## Root targets and updates
120
72
 
121
- `initial` supplies root values while following the topology's declared child
122
- defaults. It does not override those defaults. A structural root usually needs
123
- no initializer.
73
+ `{ target: targets.root, input: ... }` reconstructs root data and follows its
74
+ initial declarations using fresh input. Input is required exactly when it is
75
+ required by `Machine.start`. Machines without input omit it. Root targets reject
76
+ `data`, `decoded`, and explicit child construction.
124
77
 
125
- Use the separately named `initialConfiguration` to select a complete startup
126
- configuration, for example to start the door open:
127
-
128
- ```ts
129
- const DoorOpen = Machine.make({
130
- root: Root,
131
- events: Events,
132
- initialConfiguration: (root) => root.resolve(({ target }) =>
133
- target.from((states) => states.Open.from())
134
- )
135
- }).handle({})
136
- ```
78
+ Targeting root retains its lifecycle unless it is reentered. Put a machine-wide
79
+ reset handler at root and use `reenter: true` to exit and enter root as well as
80
+ its descendants. Reentry restarts work owned by the exited states. Without
81
+ reentry, retained root work continues; it does not automatically acquire new
82
+ construction values. Ordinary transition conflict and lifecycle rules still apply.
83
+ This does not create a new machine reference or discard history records.
137
84
 
138
- This example uses the door root and events from the first section. Every active
139
- value and region in an explicit configuration must be provided. `initial` and
140
- `initialConfiguration` cannot be combined. Use `Machine.resume` when restoring
141
- a validated snapshot, including its completion and history metadata.
85
+ `{ update: targets.root, data: ... }` instead replaces root's complete value,
86
+ retaining its active children and running work. It takes no input and does not
87
+ run initial constructors. Other source/ancestor updates follow the same rules.
142
88
 
143
- ## Construction, guards, and branches
89
+ ## Inline and named construction
144
90
 
145
- Ordinary transitions declare their destination inline. `from` constructs schema
146
- make input; `decoded` returns an already decoded value. Omit construction only
147
- when the selected state can be constructed without arguments.
91
+ Ordinary transitions stay inline:
148
92
 
149
93
  ```ts
150
- Save: {
151
- target: targets.root.Saving,
152
- guard: ({ state }) => state.draft.length > 0,
153
- from: ({ state }) => ({ requestId: state.draft })
94
+ Load: {
95
+ target: targets.root.Loading,
96
+ data: ({ event }) => ({ documentId: event.documentId })
154
97
  }
155
98
  ```
156
99
 
157
- A false guard declines the handler and allows ancestor fallback. `{ none: true }`
158
- accepts an event without changing topology. Initial entry and total choices
159
- cannot decline. `reenter: true` explicitly restarts the handler source; a value
160
- update alone retains its lifecycle and cannot request reentry.
100
+ Targeting a compound or parallel state follows its initial declarations. Event
101
+ transitions use `target`, never `initial`. `initial` names only handler startup
102
+ edges. `history` restores a declared history reference; `none: true` accepts an
103
+ event without changing its target configuration.
161
104
 
162
- Use a branch group in `make` for conditional selection, commands, or explicit
163
- nested construction. The resolver receives constructors derived from that
164
- exact declaration, so its result cannot introduce another destination.
105
+ Declare branch topology in `make` when a resolver chooses an outcome, builds an
106
+ explicit subtree, or enqueues commands:
165
107
 
166
108
  ```ts
167
- // In make:
168
109
  branches: {
169
- choose: {
170
- saving: { target: targets.root.Saving, title: "Save changes" },
171
- idle: { target: targets.root.Idle }
110
+ open: {
111
+ checkout: { target: targets.root.Checkout },
112
+ unchanged: { none: true }
172
113
  }
173
114
  }
115
+ ```
116
+
117
+ The resolver calls a constructor bound to that declaration:
174
118
 
175
- // In handle:
176
- Choose: {
177
- branches: "choose",
178
- resolve: ({ event, select }) => event.save
179
- ? select.saving.from({ requestId: event.requestId })
180
- : select.idle.from()
119
+ ```ts
120
+ Open: {
121
+ branches: "open",
122
+ resolve: ({ event, select }) => event.open
123
+ ? select.checkout({
124
+ data: { cartId: event.cartId },
125
+ states: { Review: { data: { total: event.total } } }
126
+ })
127
+ : select.unchanged()
181
128
  }
182
129
  ```
183
130
 
184
- Declare `declinable: true` if a resolver may return `decline()`. Guards and
185
- resolvers must remain synchronous and deterministic.
131
+ Objects contain computed values, not nested constructor callbacks. `data` is
132
+ schema make input; `{ decoded: true, data: value }` supplies the decoded type.
133
+ Both paths validate and report typed schema failures before committing changes.
134
+ The decoded flag applies only to its own node. Structural nodes reject data.
186
135
 
187
- An owner update replaces its entire value. A combined transition constructs
188
- both values atomically:
136
+ Omitting `states` follows declared initial children. Explicit compound
137
+ construction selects exactly one child. Entering an inactive parallel subtree
138
+ requires every region. Source-local parallel construction can select a single
139
+ region while retaining its active siblings, preserving the existing scope rules.
140
+ Names under `states` cannot collide with construction metadata.
141
+
142
+ Declared branch targets remain inspectable without executing a resolver.
143
+ Dynamically selected descendants are visible after resolution; this API does not
144
+ add static analysis of resolver bodies.
145
+
146
+ ## Retained-owner updates
147
+
148
+ An inline combined transition keeps `target` and `update` references separate:
189
149
 
190
150
  ```ts
191
151
  Save: {
192
- target: targets.root.Saving,
193
- update: targets.root,
194
- from: ({ root, event }) => ({
152
+ target: targets.root.Checkout.Saving,
153
+ update: targets.root.Checkout,
154
+ data: ({ event }) => ({
195
155
  target: { requestId: event.requestId },
196
- update: { ...root, attempts: root.attempts + 1 }
156
+ update: { cartId: event.cartId }
197
157
  })
198
158
  }
199
159
  ```
200
160
 
201
- Destination entry sees the updated owner. Use a named branch with the same
202
- `{ target, update }` declaration for nested construction or mixed methods:
203
- `select.saved.from(payload).update.decoded(ownerValue)`.
161
+ For the same pair declared as a named branch, construct both in one call:
204
162
 
205
- All destination references are paths derived by `Machine.targets(Root)`.
206
- `target` selects a descendant; `initial` enters a compound or parallel subtree
207
- using its declared initialization; `history` restores a history reference.
208
- `update: targets.root` changes root data while preserving active children.
209
- There is no transition operation that replaces an arbitrary full root
210
- configuration. Use explicit branches to keep every possible destination visible.
211
-
212
- ## Completion and history
163
+ ```ts
164
+ select.saved({
165
+ data: { requestId: event.requestId },
166
+ update: { data: { cartId: event.cartId } }
167
+ })
168
+ ```
213
169
 
214
- A compound root returns its completed direct workflow's output when that child
215
- has no `onDone` handler. A child with `onDone` first handles its completion.
216
- Nested compound states retain statechart completion rules: an arbitrary
217
- completed descendant does not make every ancestor final. Parallel roots
218
- complete when all required regions complete.
170
+ `update` is required only for a branch declaring an owner update. It is not an
171
+ arbitrary nested-state operation. The owner must be active and retained across
172
+ the transition. Both complete values validate before either is committed.
219
173
 
220
- Restoring history beneath the root preserves current root data. Restoring the
221
- root's own history can restore root-owned data. History fallback builders must
222
- construct a complete configuration containing the history owner.
174
+ ## History and lifecycle
223
175
 
224
- ## Observation and testing
176
+ History fallback uses a bound function with the same node object format:
225
177
 
226
- - `MachineRef.state` reads the complete logical root snapshot.
227
- - `MachineRef.snapshot` includes runtime status and completion information.
228
- - `MachineAtom.result` retains asynchronous startup, failure, and the successful
229
- logical snapshot. `MachineAtom.snapshot` exposes the runtime snapshot.
230
- - `AtomMachine.select` selects an optional value; `selectSnapshot` selects an
231
- optional subtree. Child inactivity remains `Option.none()`.
232
- - `MachineState` renders a typed path in React. `createMachineContext(factory)`
233
- owns a separate machine per Provider without subscribing the Provider to it.
178
+ ```ts
179
+ history: {
180
+ recent: {
181
+ default: ({ target }) => target({
182
+ states: {
183
+ Checkout: {
184
+ data: { cartId: "new" },
185
+ states: { Review: { data: { total: 0 } } }
186
+ }
187
+ }
188
+ })
189
+ }
190
+ }
191
+ ```
234
192
 
235
- The Atom bridge and child bridge no longer expose `.state`; use `.result` or a
236
- path selector. The core `MachineRef.state` contract remains available.
193
+ A fallback must explicitly construct a complete tree containing its owner,
194
+ including required ancestors and parallel siblings. Its root data is state data,
195
+ not startup input. `Machine.resume` restores a validated snapshot without rerunning
196
+ startup constructors.
237
197
 
238
- `MachineTest.run` and `MachineTest.probe` accept the same public event inputs as
239
- production sends, including deferred constructors. Traces and acknowledgements
240
- record the decoded event that was processed, including ignored events.
198
+ `guard` declines before construction. A resolver may return `decline()` only with
199
+ `declinable: true`. Effect, Stream, timer, logic, child invocation, completion,
200
+ entry/exit, and required outcome channels retain their existing contracts.
241
201
 
242
202
  ## Migration
243
203
 
244
- Replace `Machine.states(tree)` and `Machine.make({ states: States.states })`
245
- with one `Machine.state({ initial, states: tree })` descriptor and
246
- `Machine.make({ root })`. Move the old root-level handler map under
247
- `handle({ states: ... })`; place machine-wide behavior directly in `handle`.
248
- Use root `fields` to replace a wrapper state introduced only to carry shared data.
249
- Use `Machine.Snapshot<typeof root>` for the complete logical snapshot. `Machine.StateAccessors` replaces the former `Machine.DefinedStates`
250
- helper interface; it exposes paths and projections without a public state map.
251
-
252
- Replace schema arguments to `Machine.events`, `internalEvents`, and
253
- `emittedEvents` with field records, or use their explicit `FromSchemas`
254
- constructors. Replace old Atom `.state` reads with `.result`. Use
255
- `EmittedEvent`, `EmittedEvents`, `EmittedEventOf`, and `SchemaLessStateAnnotations` in place
256
- of the removed deprecated type aliases.
257
-
258
- Encoded snapshots now use version 2 and include the root at path `""`.
259
- Version 1 payloads must be explicitly migrated; the decoder rejects them.
204
+ - Root initial constructors can read `input`; remove root fields used only to
205
+ forward that input to the initial child.
206
+ - Replace event `{ initial: reference, data }` with `{ target: reference, data }`.
207
+ - Replace `select.branch.from(value)` with `select.branch({ data: value })`.
208
+ - Replace `.decoded(value)` with `({ decoded: true, data: value })`.
209
+ - Replace child callbacks with `states: { Child: { data, states } }`.
210
+ - Replace `.update.from(value)` chaining with `update: { data: value }` inside
211
+ the same selector call.
212
+ - Replace history fallback chains with `target({ states: ... })`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/effect-machine",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
4
4
  "description": "Schema-first state machines and statecharts for Effect",
5
5
  "author": "Sandro Maglione",
6
6
  "repository": {