@typeonce/effect-machine 0.46.0 → 0.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/AGENTS.md +1823 -0
  2. package/CLAUDE.md +1823 -0
  3. package/README.md +100 -77
  4. package/ai-docs/README.md +18 -0
  5. package/ai-docs/src/10_modeling/01_create-a-machine.ts +51 -0
  6. package/ai-docs/src/10_modeling/02_branch-on-an-event.ts +55 -0
  7. package/ai-docs/src/10_modeling/03_update-retained-state.ts +58 -0
  8. package/ai-docs/src/10_modeling/04_verify-after-changing.ts +29 -0
  9. package/{docs/agent-guide.md → ai-docs/src/10_modeling/index.md} +234 -155
  10. package/{docs/root-api.md → ai-docs/src/20_root-api/index.md} +29 -57
  11. package/{docs/effect-atom-react.md → ai-docs/src/30_react/index.md} +42 -49
  12. package/{docs/machine-review.md → ai-docs/src/40_review/index.md} +42 -40
  13. package/ai-docs/src/index.md +7 -0
  14. package/ai-docs/tsconfig.json +22 -0
  15. package/dist/Machine.d.ts +1195 -1474
  16. package/dist/Machine.d.ts.map +1 -1
  17. package/dist/Machine.js +366 -214
  18. package/dist/Machine.js.map +1 -1
  19. package/dist/internal/machine/atom.js.map +1 -1
  20. package/dist/internal/machine/cluster.js.map +1 -1
  21. package/dist/internal/machine/command.d.ts +8 -0
  22. package/dist/internal/machine/command.d.ts.map +1 -1
  23. package/dist/internal/machine/command.js +2 -2
  24. package/dist/internal/machine/command.js.map +1 -1
  25. package/dist/internal/machine/configuration.d.ts +21 -5
  26. package/dist/internal/machine/configuration.d.ts.map +1 -1
  27. package/dist/internal/machine/configuration.js +1 -0
  28. package/dist/internal/machine/configuration.js.map +1 -1
  29. package/dist/internal/machine/construction.js.map +1 -1
  30. package/dist/internal/machine/declaration.d.ts +2 -1
  31. package/dist/internal/machine/declaration.d.ts.map +1 -1
  32. package/dist/internal/machine/declaration.js +28 -46
  33. package/dist/internal/machine/declaration.js.map +1 -1
  34. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  35. package/dist/internal/machine/executionPlan.js +23 -16
  36. package/dist/internal/machine/executionPlan.js.map +1 -1
  37. package/dist/internal/machine/implementation.d.ts +2 -0
  38. package/dist/internal/machine/implementation.d.ts.map +1 -1
  39. package/dist/internal/machine/implementation.js.map +1 -1
  40. package/dist/internal/machine/initialDeclaration.d.ts +2 -0
  41. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  42. package/dist/internal/machine/initialDeclaration.js +15 -0
  43. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  44. package/dist/internal/machine/invocation.d.ts.map +1 -1
  45. package/dist/internal/machine/invocation.js +25 -19
  46. package/dist/internal/machine/invocation.js.map +1 -1
  47. package/dist/internal/machine/invocationEvent.d.ts +34 -17
  48. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  49. package/dist/internal/machine/invocationEvent.js +16 -4
  50. package/dist/internal/machine/invocationEvent.js.map +1 -1
  51. package/dist/internal/machine/machine.d.ts +5 -22
  52. package/dist/internal/machine/machine.d.ts.map +1 -1
  53. package/dist/internal/machine/machine.js +157 -119
  54. package/dist/internal/machine/machine.js.map +1 -1
  55. package/dist/internal/machine/planner.d.ts +15 -4
  56. package/dist/internal/machine/planner.d.ts.map +1 -1
  57. package/dist/internal/machine/planner.js +18 -21
  58. package/dist/internal/machine/planner.js.map +1 -1
  59. package/dist/internal/machine/process.d.ts +2 -0
  60. package/dist/internal/machine/process.d.ts.map +1 -1
  61. package/dist/internal/machine/process.js +2 -0
  62. package/dist/internal/machine/process.js.map +1 -1
  63. package/dist/internal/machine/protocol.js.map +1 -1
  64. package/dist/internal/machine/runtime.d.ts.map +1 -1
  65. package/dist/internal/machine/runtime.js.map +1 -1
  66. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -1
  68. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  69. package/dist/internal/machine/runtimeProtocol.d.ts +26 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  71. package/dist/internal/machine/runtimeProtocol.js +71 -0
  72. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  73. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  74. package/dist/internal/machine/stateDefinition.js +0 -14
  75. package/dist/internal/machine/stateDefinition.js.map +1 -1
  76. package/dist/internal/machine/symbols.d.ts +9 -0
  77. package/dist/internal/machine/symbols.d.ts.map +1 -1
  78. package/dist/internal/machine/symbols.js.map +1 -1
  79. package/dist/internal/machine/topology.d.ts +18 -9
  80. package/dist/internal/machine/topology.d.ts.map +1 -1
  81. package/dist/internal/machine/topology.js +16 -1
  82. package/dist/internal/machine/topology.js.map +1 -1
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  84. package/dist/internal/testing/machine/arbitrary.js +2 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  86. package/dist/internal/testing/machine/check.d.ts +17 -0
  87. package/dist/internal/testing/machine/check.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/check.js +371 -0
  89. package/dist/internal/testing/machine/check.js.map +1 -0
  90. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/exploration.js.map +1 -1
  92. package/dist/internal/testing/machine/finiteModel.d.ts +14 -13
  93. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  94. package/dist/internal/testing/machine/finiteModel.js +21 -23
  95. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  96. package/dist/internal/testing/machine/runtime.d.ts +19 -88
  97. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  98. package/dist/internal/testing/machine/runtime.js +0 -19
  99. package/dist/internal/testing/machine/runtime.js.map +1 -1
  100. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -1
  101. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  102. package/dist/internal/testing/machine/verification.js.map +1 -1
  103. package/dist/testing/MachineTest.d.ts +349 -139
  104. package/dist/testing/MachineTest.d.ts.map +1 -1
  105. package/dist/testing/MachineTest.js +201 -136
  106. package/dist/testing/MachineTest.js.map +1 -1
  107. package/dist/unstable/cluster/ClusterMachine.d.ts +9 -14
  108. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  109. package/dist/unstable/cluster/ClusterMachine.js +9 -14
  110. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  111. package/dist/unstable/reactivity/AtomMachine.d.ts +169 -80
  112. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  113. package/dist/unstable/reactivity/AtomMachine.js +165 -76
  114. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  115. package/package.json +11 -9
  116. package/src/Machine.ts +1141 -2130
  117. package/src/internal/machine/atom.ts +3 -3
  118. package/src/internal/machine/cluster.ts +2 -2
  119. package/src/internal/machine/command.ts +10 -4
  120. package/src/internal/machine/configuration.ts +16 -17
  121. package/src/internal/machine/construction.ts +1 -1
  122. package/src/internal/machine/declaration.ts +25 -50
  123. package/src/internal/machine/executionPlan.ts +90 -56
  124. package/src/internal/machine/implementation.ts +3 -1
  125. package/src/internal/machine/initialDeclaration.ts +16 -0
  126. package/src/internal/machine/invocation.ts +38 -44
  127. package/src/internal/machine/invocationEvent.ts +46 -20
  128. package/src/internal/machine/machine.ts +217 -243
  129. package/src/internal/machine/planner.ts +72 -106
  130. package/src/internal/machine/process.ts +12 -0
  131. package/src/internal/machine/protocol.ts +6 -6
  132. package/src/internal/machine/runtime.ts +1 -5
  133. package/src/internal/machine/runtimeCompiled.ts +2 -2
  134. package/src/internal/machine/runtimeGeneric.ts +2 -4
  135. package/src/internal/machine/runtimeProtocol.ts +80 -4
  136. package/src/internal/machine/stateDefinition.ts +0 -39
  137. package/src/internal/machine/symbols.ts +11 -0
  138. package/src/internal/machine/topology.ts +40 -18
  139. package/src/internal/testing/machine/arbitrary.ts +2 -0
  140. package/src/internal/testing/machine/check.ts +460 -0
  141. package/src/internal/testing/machine/exploration.ts +4 -5
  142. package/src/internal/testing/machine/finiteModel.ts +40 -42
  143. package/src/internal/testing/machine/runtime.ts +31 -170
  144. package/src/internal/testing/machine/runtimeInvariant.ts +3 -3
  145. package/src/internal/testing/machine/verification.ts +14 -14
  146. package/src/testing/MachineTest.ts +366 -145
  147. package/src/unstable/cluster/ClusterMachine.ts +9 -14
  148. package/src/unstable/reactivity/AtomMachine.ts +167 -78
@@ -39,7 +39,7 @@ import * as Construction from "./construction.js"
39
39
  import { failPlanning, InfiniteTransitionError, MachineSchemaDecodeError, toStartupFailure } from "./errors.js"
40
40
  import { StoppedError } from "./errors.js"
41
41
  import type { PlanningError, StartupError } from "./errors.js"
42
- import { type CapturedStateConfig, toImpl } from "./implementation.js"
42
+ import { toImpl } from "./implementation.js"
43
43
  import { isDataInitializer } from "./initialDeclaration.js"
44
44
  import { getStateInitializeValues, makeStateInitializeBuilder } from "./initialization.js"
45
45
  import * as InvocationDefinition from "./invocationDefinition.js"
@@ -48,6 +48,7 @@ import { decodeEventSync, decodeInputSync, decodeStateValueSync } from "./protoc
48
48
  import { InitialEventTypeId } from "./symbols.js"
49
49
  import {
50
50
  getNode,
51
+ type HistoryTarget,
51
52
  type InitialTarget as InitialTargetInstruction,
52
53
  isChoiceTarget,
53
54
  isCombinedTarget,
@@ -59,8 +60,10 @@ import {
59
60
  isStateUpdate,
60
61
  isTarget,
61
62
  makeChoiceTarget,
63
+ makeResolvedTarget,
62
64
  makeStateInput,
63
65
  makeTarget,
66
+ type TargetSnapshotSlot,
64
67
  TargetSnapshotTypeId
65
68
  } from "./topology.js"
66
69
  import type {
@@ -313,7 +316,7 @@ const completeHistoryConfiguration = (
313
316
  next = normalizeTargetConfigurationSync(
314
317
  machine,
315
318
  next,
316
- (resolved?.target ?? routed) as Machine.Snapshot<any> | Machine.Target<any, any>
319
+ resolved?.target ?? routed
317
320
  )
318
321
  if (resolved !== undefined) {
319
322
  commands.push(...resolved.commands)
@@ -450,7 +453,7 @@ export function resolveInitialConfiguration(
450
453
  for (const path of target.children?.keys() ?? []) {
451
454
  const node = getNode(machine, path)
452
455
  if (node.type !== "choice") continue
453
- const choice = resolveChoiceTarget(machine, partial, makeChoiceTarget(path, node.parent!), event)
456
+ const choice = resolveChoiceTarget(machine, partial, makeChoiceTarget(path, node.parent), event)
454
457
  for (const routed of [choice.target, ...choice.additionalTargets]) {
455
458
  const resolved = isInitialTarget(routed) ?
456
459
  resolveInitialTarget(machine, partial, routed, event)
@@ -460,7 +463,7 @@ export function resolveInitialConfiguration(
460
463
  partial = normalizeTargetConfigurationSync(
461
464
  machine,
462
465
  partial,
463
- (resolved?.target ?? routed) as Machine.Target<any, any>
466
+ resolved?.target ?? routed
464
467
  )
465
468
  if (resolved !== undefined) {
466
469
  commands.push(...resolved.commands)
@@ -494,10 +497,7 @@ export function resolveInitialTarget(
494
497
  const completed = resolveInitialConfiguration(machine, configuration, target, event)
495
498
  const snapshot = snapshotFromConfigurationAtPath(machine, completed.configuration, target.path)
496
499
  return {
497
- target: makeTarget(target.path as any, snapshot.value as any, {
498
- snapshot: snapshot as any,
499
- values: target.values as any
500
- }),
500
+ target: makeResolvedTarget(target.path, snapshot.value, { snapshot, values: target.values }),
501
501
  commands: completed.commands,
502
502
  raisedEvents: completed.raisedEvents,
503
503
  emittedEvents: completed.emittedEvents,
@@ -526,10 +526,7 @@ function resolveHistoryTarget(
526
526
  const values = Object.fromEntries(completed.configuration.values)
527
527
  if (target.parent !== "" && configuration.active.has("")) delete values[""]
528
528
  return {
529
- target: makeTarget(target.parent as any, snapshot.value as any, {
530
- snapshot: snapshot as any,
531
- values: values as any
532
- }),
529
+ target: makeResolvedTarget(target.parent, snapshot.value, { snapshot, values }),
533
530
  commands: completed.commands,
534
531
  raisedEvents: completed.raisedEvents,
535
532
  emittedEvents: completed.emittedEvents,
@@ -565,20 +562,18 @@ function resolveHistoryTarget(
565
562
  event
566
563
  )
567
564
  let fallbackConfiguration = choiceResolution === undefined
568
- ? normalizeConfigurationSync(machine, collected.state as any)
565
+ ? normalizeConfigurationSync(machine, collected.state)
569
566
  : normalizeTargetConfigurationSync(machine, {
570
567
  active: new Set(),
571
568
  values: new Map(),
572
569
  outputs: new Map(),
573
570
  history: configuration.history
574
- }, choiceResolution.target as any)
571
+ }, choiceResolution.target)
575
572
  for (const additionalTarget of choiceResolution?.additionalTargets ?? []) {
576
573
  fallbackConfiguration = normalizeTargetConfigurationSync(
577
574
  machine,
578
575
  fallbackConfiguration,
579
- additionalTarget as
580
- | Machine.Snapshot<any>
581
- | Machine.Target<any, string>
576
+ additionalTarget
582
577
  )
583
578
  }
584
579
  if (!fallbackConfiguration.active.has(target.parent)) {
@@ -590,10 +585,7 @@ function resolveHistoryTarget(
590
585
  const values = Object.fromEntries(fallbackConfiguration.values)
591
586
  if (target.parent !== "" && configuration.active.has("")) delete values[""]
592
587
  return {
593
- target: makeTarget(target.parent as any, snapshot.value as any, {
594
- snapshot: snapshot as any,
595
- values: values as any
596
- }),
588
+ target: makeResolvedTarget(target.parent, snapshot.value, { snapshot, values }),
597
589
  commands: [...collected.commands, ...(choiceResolution?.commands ?? [])],
598
590
  raisedEvents: [...collected.raisedEvents, ...(choiceResolution?.raisedEvents ?? [])],
599
591
  emittedEvents: [...collected.emittedEvents, ...(choiceResolution?.emittedEvents ?? [])],
@@ -885,12 +877,7 @@ const selectAlwaysTransitions = <
885
877
  sourcePath: path,
886
878
  leafPath: leaf,
887
879
  trigger: { type: "always" },
888
- transition: always as unknown as MicrostepTransition<
889
- States,
890
- E,
891
- R,
892
- ConstructionContext<Machine.AlwaysContext<States, Events, Emits, Machine.StateIdentifier<States>>>
893
- >,
880
+ transition: always,
894
881
  context: {
895
882
  ...resolveMachineReferences(machine, configuration),
896
883
  state: configuration.values.get(path) as Machine.StateByIdentifier<
@@ -961,12 +948,7 @@ const selectDoneTransitions = <
961
948
  sourcePath: completion.path,
962
949
  leafPath: getActiveLeafPathFrom(machine, configuration, completion.path),
963
950
  trigger: { type: "done" },
964
- transition: onDone as unknown as MicrostepTransition<
965
- States,
966
- E,
967
- R,
968
- ConstructionContext<Machine.DoneContext<States, Events, Emits, Machine.StateIdentifier<States>>>
969
- >,
951
+ transition: onDone,
970
952
  context: makeDoneContext<States, Events, Emits, Machine.StateIdentifier<States>>(
971
953
  machine,
972
954
  configuration,
@@ -1042,29 +1024,14 @@ const selectEventTransitions = <
1042
1024
  sourcePath: path,
1043
1025
  leafPath: leaf,
1044
1026
  trigger: { type: "event", event: event._tag },
1045
- transition: transition as unknown as MicrostepTransition<
1046
- States,
1047
- E,
1048
- R,
1049
- ConstructionContext<
1050
- Machine.HandlerContext<
1051
- States,
1052
- Events,
1053
- Emits,
1054
- Machine.StateIdentifier<States>,
1055
- Machine.TagOf<Events[number]>,
1056
- E,
1057
- R
1058
- >
1059
- >
1060
- >,
1027
+ transition,
1061
1028
  context: makeTransitionContext<
1062
1029
  States,
1063
1030
  Events,
1064
1031
  Emits,
1065
1032
  Machine.StateIdentifier<States>,
1066
1033
  Machine.TagOf<Events[number]>
1067
- >(machine as any, configuration, path, event, capturedSnapshot())
1034
+ >(machine, configuration, path, event, capturedSnapshot())
1068
1035
  })
1069
1036
  evaluatedSources.set(path, candidate)
1070
1037
  }
@@ -1091,8 +1058,11 @@ const selectInvocationTransition = <
1091
1058
  configuration: ActiveConfiguration,
1092
1059
  event: InvocationEvent.InvocationEvent
1093
1060
  ): ReadonlyArray<SelectedTransition<States, E, R, any>> => {
1094
- if (!configuration.active.has(event.path)) return []
1095
- const config = toImpl(machine).handlers[event.path] as CapturedStateConfig | undefined
1061
+ // An outcome belongs to the activation of its owner that started it. One
1062
+ // queued before that owner exited is discarded, even after the same path and
1063
+ // id are entered again.
1064
+ if (!InvocationEvent.isCurrent(event) || !configuration.active.has(event.path)) return []
1065
+ const config = toImpl(machine).handlers[event.path]
1096
1066
  const invoke = InvocationDefinition.definitions(config?.invoke).find((definition) => {
1097
1067
  const id = "child" in definition ? definition.child?.id : definition.id
1098
1068
  return String(id) === event.id
@@ -1127,19 +1097,14 @@ const selectInvocationTransition = <
1127
1097
  sourcePath: event.path,
1128
1098
  leafPath: getActiveLeafPathFrom(machine, configuration, event.path),
1129
1099
  trigger: { type: "invoke", id: event.id, outcome: event.type },
1130
- transition: transition as unknown as MicrostepTransition<States, E, R, any>,
1100
+ transition,
1131
1101
  context
1132
1102
  })
1133
1103
  return candidate === undefined ? [] : [candidate]
1134
1104
  }
1135
1105
 
1136
- export const getTargetNodePath = <const States extends Machine.StateSchemas>(
1137
- target:
1138
- | Machine.Snapshot<States>
1139
- | Machine.Target<States, Machine.StateIdentifier<States>>
1140
- | Machine.HistoryTarget<States, Machine.HistoryIdentifier<States>>
1141
- | Machine.ChoiceTarget<States, Machine.ChoiceIdentifier<States>>
1142
- ): string => {
1106
+ /** Reads the state path addressed by a transition result, failing for any other value. */
1107
+ export const getTargetNodePath = (target: unknown): string => {
1143
1108
  if (isHistoryTarget(target) || isChoiceTarget(target)) {
1144
1109
  return String(target.path)
1145
1110
  }
@@ -1183,16 +1148,17 @@ const hasPathIntersection = (left: ReadonlyArray<string>, right: ReadonlyArray<s
1183
1148
  return false
1184
1149
  }
1185
1150
 
1186
- export const sortEvaluatedTransitions = <
1187
- const States extends Machine.StateSchemas,
1188
- Event,
1189
- E,
1190
- R,
1191
- Context
1192
- >(
1151
+ /** The fields conflict resolution reads, shared by the generic and indexed planners. */
1152
+ export interface ConflictCandidate {
1153
+ readonly selection: { readonly sourcePath: string }
1154
+ readonly update: { readonly path: string } | undefined
1155
+ readonly exitPaths: ReadonlyArray<string>
1156
+ }
1157
+
1158
+ export const sortEvaluatedTransitions = <Transition extends Pick<ConflictCandidate, "selection">>(
1193
1159
  machine: Machine.Any,
1194
- transitions: Iterable<EvaluatedTransition<States, Event, E, R, Context>>
1195
- ): ReadonlyArray<EvaluatedTransition<States, Event, E, R, Context>> =>
1160
+ transitions: Iterable<Transition>
1161
+ ): ReadonlyArray<Transition> =>
1196
1162
  Array.from(transitions)
1197
1163
  .sort((left, right) => compareDocumentOrder(machine, left.selection.sourcePath, right.selection.sourcePath))
1198
1164
 
@@ -1210,20 +1176,14 @@ const removePreemptedAncestorSelections = <
1210
1176
  )
1211
1177
  )
1212
1178
 
1213
- export const removeConflictingTransitions = <
1214
- const States extends Machine.StateSchemas,
1215
- Event,
1216
- E,
1217
- R,
1218
- Context
1219
- >(
1179
+ export const removeConflictingTransitions = <Transition extends ConflictCandidate>(
1220
1180
  machine: Machine.Any,
1221
- transitions: ReadonlyArray<EvaluatedTransition<States, Event, E, R, Context>>
1222
- ): ReadonlyArray<EvaluatedTransition<States, Event, E, R, Context>> => {
1223
- const filtered: Array<EvaluatedTransition<States, Event, E, R, Context>> = []
1181
+ transitions: ReadonlyArray<Transition>
1182
+ ): ReadonlyArray<Transition> => {
1183
+ const filtered: Array<Transition> = []
1224
1184
  for (const transition of sortEvaluatedTransitions(machine, transitions)) {
1225
1185
  let preempted = false
1226
- const transitionsToRemove = new Set<EvaluatedTransition<States, Event, E, R, Context>>()
1186
+ const transitionsToRemove = new Set<Transition>()
1227
1187
  for (const selected of filtered) {
1228
1188
  const writesSameState = transition.update !== undefined && selected.update !== undefined &&
1229
1189
  transition.update.path === selected.update.path
@@ -1287,14 +1247,14 @@ const choiceFromTarget = (
1287
1247
 
1288
1248
  const withChoiceValues = (target: unknown, values: Readonly<Record<string, unknown>>): unknown => {
1289
1249
  if (isChoiceTarget(target)) {
1290
- return makeChoiceTarget(target.path, target.parent, { ...values, ...(target.values ?? {}) })
1250
+ return makeChoiceTarget(target.path, target.parent, { ...values, ...target.values })
1291
1251
  }
1292
1252
  if (isInitialTarget(target)) return { ...target, values: { ...values, ...target.values } }
1293
1253
  if (!isTarget(target) || Object.keys(values).length === 0) return target
1294
- const snapshot = target[TargetSnapshotTypeId]
1254
+ const snapshot = (target as TargetSnapshotSlot<Machine.SnapshotByIdentifier<any, any>>)[TargetSnapshotTypeId]
1295
1255
  return makeTarget(target.path, target.value, {
1296
1256
  ...(snapshot === undefined ? {} : { snapshot }),
1297
- values: { ...values, ...(target.values ?? {}) }
1257
+ values: { ...values, ...target.values }
1298
1258
  })
1299
1259
  }
1300
1260
 
@@ -1309,6 +1269,12 @@ interface ResolvedChoiceTransition {
1309
1269
  readonly updates: ReadonlyArray<string>
1310
1270
  }
1311
1271
 
1272
+ /** A target resolved to concrete state paths, before configuration normalization. */
1273
+ type ResolvedTarget = Machine.Target<any, string> | Machine.AtomicSnapshot<string, unknown>
1274
+
1275
+ /** A route selected by choice resolution; initial and history routes are resolved by the caller. */
1276
+ type ChoiceRoute = ResolvedTarget | HistoryTarget | InitialTargetInstruction
1277
+
1312
1278
  function resolveChoiceTarget(
1313
1279
  machine: Machine.Any,
1314
1280
  configuration: ActiveConfiguration,
@@ -1316,7 +1282,7 @@ function resolveChoiceTarget(
1316
1282
  event: unknown
1317
1283
  ) {
1318
1284
  const pending: Array<unknown> = [initialTarget]
1319
- const resolvedTargets: Array<unknown> = []
1285
+ const resolvedTargets: Array<ChoiceRoute> = []
1320
1286
  const commands: Array<RuntimeCommand> = []
1321
1287
  const raisedEvents: Array<unknown> = []
1322
1288
  const emittedEvents: Array<unknown> = []
@@ -1378,7 +1344,7 @@ function resolveChoiceTarget(
1378
1344
  throw new Error(`Machine choice resolver for "${node.path}" must return a target`)
1379
1345
  }
1380
1346
  validateDeclaredTransitionTarget(node.path, { type: "choice" }, choice.targets, collected.state)
1381
- const returnedPath = getTargetNodePath(collected.state as any)
1347
+ const returnedPath = getTargetNodePath(collected.state)
1382
1348
  current = withChoiceValues(collected.state, extracted.values)
1383
1349
  const nested = choiceFromTarget(current)
1384
1350
  transitions.push({
@@ -1417,7 +1383,7 @@ const collectEvaluatedTransition = <
1417
1383
  Event,
1418
1384
  E,
1419
1385
  R,
1420
- Context
1386
+ Context extends { readonly event?: unknown }
1421
1387
  >(
1422
1388
  machine: Machine.Any,
1423
1389
  state: ActiveConfiguration,
@@ -1431,7 +1397,7 @@ const collectEvaluatedTransition = <
1431
1397
  selection.transition.evaluate
1432
1398
  )
1433
1399
  if (transitionResult.declined) {
1434
- throw new Error("Machine transition returned decline without declaring declinable: true")
1400
+ throw new Error("Machine transition declined where a transition must be selected")
1435
1401
  }
1436
1402
  const combined = isCombinedTarget(transitionResult.state) ? transitionResult.state : undefined
1437
1403
  const transitionState = combined?.target ?? transitionResult.state
@@ -1476,11 +1442,11 @@ const collectEvaluatedTransition = <
1476
1442
  machine,
1477
1443
  constructionState,
1478
1444
  unresolvedTarget,
1479
- (selection.context as any).event
1445
+ selection.context.event
1480
1446
  )
1481
1447
  const choiceResolvedTarget = choiceResolution?.target ?? unresolvedTarget
1482
1448
  const initialResolution = choiceResolvedTarget !== undefined && isInitialTarget(choiceResolvedTarget)
1483
- ? resolveInitialTarget(machine, constructionState, choiceResolvedTarget, (selection.context as any).event)
1449
+ ? resolveInitialTarget(machine, constructionState, choiceResolvedTarget, selection.context.event)
1484
1450
  : undefined
1485
1451
  const routedTarget = initialResolution?.target ?? choiceResolvedTarget
1486
1452
  let historyResolution: {
@@ -1514,7 +1480,7 @@ const collectEvaluatedTransition = <
1514
1480
  machine,
1515
1481
  stateAtHistoryResolution,
1516
1482
  routedTarget,
1517
- (selection.context as any).event
1483
+ selection.context.event
1518
1484
  )
1519
1485
  }
1520
1486
  const target: Machine.Snapshot<States> | Machine.Target<States, Machine.StateIdentifier<States>> | undefined =
@@ -1530,18 +1496,16 @@ const collectEvaluatedTransition = <
1530
1496
  const additionalTargetRaisedEvents: Array<unknown> = []
1531
1497
  const additionalTargetEmittedEvents: Array<unknown> = []
1532
1498
  const additionalTargetChoiceTransitions: Array<ResolvedChoiceTransition> = []
1533
- const additionalChoiceTargets: Array<
1534
- Machine.Snapshot<States> | Machine.Target<States, Machine.StateIdentifier<States>>
1535
- > = []
1499
+ const additionalChoiceTargets: Array<ResolvedTarget> = []
1536
1500
  for (const additionalTarget of choiceResolution?.additionalTargets ?? []) {
1537
1501
  if (isInitialTarget(additionalTarget)) {
1538
1502
  const resolved = resolveInitialTarget(
1539
1503
  machine,
1540
1504
  state,
1541
1505
  additionalTarget,
1542
- (selection.context as any).event
1506
+ selection.context.event
1543
1507
  )
1544
- additionalChoiceTargets.push(resolved.target as any)
1508
+ additionalChoiceTargets.push(resolved.target)
1545
1509
  additionalTargetActions.push(...resolved.commands)
1546
1510
  additionalTargetRaisedEvents.push(...resolved.raisedEvents)
1547
1511
  additionalTargetEmittedEvents.push(...resolved.emittedEvents)
@@ -1549,16 +1513,16 @@ const collectEvaluatedTransition = <
1549
1513
  continue
1550
1514
  }
1551
1515
  if (!isHistoryTarget(additionalTarget)) {
1552
- additionalChoiceTargets.push(additionalTarget as any)
1516
+ additionalChoiceTargets.push(additionalTarget)
1553
1517
  continue
1554
1518
  }
1555
1519
  const resolved = resolveHistoryTarget(
1556
1520
  machine,
1557
1521
  state,
1558
1522
  additionalTarget,
1559
- (selection.context as any).event
1523
+ selection.context.event
1560
1524
  )
1561
- additionalChoiceTargets.push(resolved.target as any)
1525
+ additionalChoiceTargets.push(resolved.target)
1562
1526
  additionalTargetActions.push(...resolved.commands)
1563
1527
  additionalTargetRaisedEvents.push(...resolved.raisedEvents)
1564
1528
  additionalTargetEmittedEvents.push(...resolved.emittedEvents)
@@ -1574,9 +1538,9 @@ const collectEvaluatedTransition = <
1574
1538
  ...state,
1575
1539
  values: new Map(state.values).set(update.path, update.value)
1576
1540
  }
1577
- : normalizeTargetConfigurationSync<States>(machine, state, target)
1541
+ : normalizeTargetConfigurationSync(machine, state, target)
1578
1542
  for (const additionalTarget of additionalChoiceTargets) {
1579
- stateAfterTransition = normalizeTargetConfigurationSync<States>(
1543
+ stateAfterTransition = normalizeTargetConfigurationSync(
1580
1544
  machine,
1581
1545
  stateAfterTransition,
1582
1546
  additionalTarget
@@ -1843,7 +1807,7 @@ const canSync = (
1843
1807
  const decodedEvent = decodeEventSync(machine, event)
1844
1808
  if (isFinalState(machine, state)) return false
1845
1809
  const configuration = normalizeConfigurationSync(machine, state)
1846
- return selectEventTransitions(machine, configuration, decodedEvent as any).length > 0
1810
+ return selectEventTransitions(machine, configuration, decodedEvent).length > 0
1847
1811
  }
1848
1812
 
1849
1813
  const microstep = (
@@ -2046,7 +2010,7 @@ const settle = (
2046
2010
  throw new Error("Machine reached a terminal configuration without a completed root output")
2047
2011
  }
2048
2012
  completedTerminal = true
2049
- finalOutput = currentState.outputs.get(root) as any
2013
+ finalOutput = currentState.outputs.get(root)
2050
2014
  break
2051
2015
  }
2052
2016
 
@@ -2109,7 +2073,7 @@ const settle = (
2109
2073
  microsteps
2110
2074
  }
2111
2075
  return completedTerminal
2112
- ? { ...result, done: true as const, output: finalOutput as any }
2076
+ ? { ...result, done: true as const, output: finalOutput }
2113
2077
  : { ...result, done: false as const, output: undefined }
2114
2078
  }
2115
2079
 
@@ -2120,6 +2084,8 @@ const macrostepConfiguration = (
2120
2084
  ) => {
2121
2085
  const decodedEvent = InvocationEvent.isInvocationEvent(event) ? event : decodeEventSync(machine, event)
2122
2086
  if (isActiveFinalConfiguration(machine, configuration)) {
2087
+ // Completion contexts receive the triggering event, including private invocation events
2088
+ // that the public lifecycle event type does not model.
2123
2089
  const completed = completeConfigurationSync(machine, configuration, decodedEvent as any)
2124
2090
  const root = getRootPath(machine, completed.configuration)
2125
2091
  if (!completed.configuration.outputs.has(root)) {
@@ -2132,7 +2098,7 @@ const macrostepConfiguration = (
2132
2098
  emittedEvents: [],
2133
2099
  microsteps: [],
2134
2100
  done: true as const,
2135
- output: completed.configuration.outputs.get(root) as any
2101
+ output: completed.configuration.outputs.get(root)
2136
2102
  }
2137
2103
  }
2138
2104
 
@@ -2157,7 +2123,7 @@ const macrostepConfiguration = (
2157
2123
  const step = microstep(
2158
2124
  machine,
2159
2125
  configuration,
2160
- decodedEvent as any,
2126
+ decodedEvent,
2161
2127
  selections
2162
2128
  )
2163
2129
  const commands = [...step.commands]
@@ -2165,7 +2131,7 @@ const macrostepConfiguration = (
2165
2131
  const emittedEvents = [...step.emittedEvents]
2166
2132
  const microsteps = [step]
2167
2133
  return {
2168
- ...settle(machine, step.next, decodedEvent as any, commands, raisedEvents, emittedEvents, microsteps),
2134
+ ...settle(machine, step.next, decodedEvent, commands, raisedEvents, emittedEvents, microsteps),
2169
2135
  event: decodedEvent
2170
2136
  }
2171
2137
  }
@@ -797,6 +797,18 @@ export const resumeWithRuntimeStrategyForTesting = (
797
797
  machine.id === undefined ? undefined : { id: machine.id }
798
798
  )
799
799
 
800
+ /** @internal Test-only runtime strategy selection for a prepared resumed machine. */
801
+ export const prepareResumedWithRuntimeStrategyForTesting = (
802
+ machine: Machine.Any,
803
+ snapshot: Machine.Snapshot<any>,
804
+ strategy: internalRuntime.ProcessRuntimeStrategy
805
+ ): Effect.Effect<internalRuntimeProtocol.PreparedProcess<any, any, any, any, any, any, any>, any, any> =>
806
+ internalRuntime.prepareProcessWithStrategyForTesting(
807
+ toResumedProcessLogic(machine, snapshot),
808
+ strategy,
809
+ machine.id === undefined ? undefined : { id: machine.id }
810
+ )
811
+
800
812
  // The public `Machine` module owns the typed start, prepare, and resume
801
813
  // signatures. These implementations are the erased boundary they specialize.
802
814
  export const start = (
@@ -75,7 +75,7 @@ const getBoundaryResultDecoder = (schema: Schema.Top): BoundaryResultDecoder =>
75
75
  if (cached !== undefined) {
76
76
  return cached
77
77
  }
78
- const decoder = Schema.decodeUnknownResult(Schema.toType(schema)) as BoundaryResultDecoder
78
+ const decoder = Schema.decodeUnknownResult(Schema.toType(schema))
79
79
  boundaryResultDecoderCache.set(key, decoder)
80
80
  return decoder
81
81
  }
@@ -123,7 +123,7 @@ const getEventProtocolDefinition = (
123
123
  protocol: Machine.EventProtocol.Any,
124
124
  expectedKind?: Machine.EventProtocolKind
125
125
  ): EventProtocolDefinition => {
126
- const definition = eventProtocolDefinitions.get(protocol as object)
126
+ const definition = eventProtocolDefinitions.get(protocol)
127
127
  if (definition === undefined) {
128
128
  throw new Error(
129
129
  "Machine expected an event protocol created with Machine.events, Machine.internalEvents, or Machine.emittedEvents"
@@ -285,7 +285,7 @@ export const makeEventProtocol = <
285
285
  ): Machine.EventProtocol<Kind, Schemas> => {
286
286
  const ownedSchemas = Object.freeze(Array.from(schemas)) as unknown as Schemas
287
287
  const protocol = eventConstructors(kind, ownedSchemas) as Machine.EventProtocol<Kind, Schemas>
288
- eventProtocolDefinitions.set(protocol as object, { kind, schemas: ownedSchemas })
288
+ eventProtocolDefinitions.set(protocol, { kind, schemas: ownedSchemas })
289
289
  return Object.freeze(protocol) as Machine.EventProtocol<Kind, Schemas>
290
290
  }
291
291
 
@@ -333,7 +333,7 @@ const makeBoundarySync = <A>(
333
333
  options: DecodeBoundaryOptions
334
334
  ): A => {
335
335
  try {
336
- return schema.make(input as never) as A
336
+ return schema.make(input) as A
337
337
  } catch (cause) {
338
338
  const issue = cause instanceof Error ? cause.cause : undefined
339
339
  throw new MachineSchemaDecodeError({
@@ -396,7 +396,7 @@ const decodeEventConstruction = (
396
396
  if (
397
397
  definition === undefined ||
398
398
  (boundary === "emission" ? definition.kind !== "emitted" : definition.kind === "emitted") ||
399
- !constructors.has(definition.schema as object)
399
+ !constructors.has(definition.schema)
400
400
  ) {
401
401
  return Effect.fail(eventConstructionProtocolError(machine, construction, boundary))
402
402
  }
@@ -430,7 +430,7 @@ const decodeEventConstructionSync = (
430
430
  if (
431
431
  definition === undefined ||
432
432
  (boundary === "emission" ? definition.kind !== "emitted" : definition.kind === "emitted") ||
433
- !constructors.has(definition.schema as object)
433
+ !constructors.has(definition.schema)
434
434
  ) {
435
435
  throw eventConstructionProtocolError(machine, construction, boundary)
436
436
  }
@@ -234,11 +234,7 @@ const prepareProcessWithStrategy = Effect.fnUntraced(function*<
234
234
  const start = yield* Effect.cached(
235
235
  ownedByScope(initialize).pipe(
236
236
  Effect.onExit((exit) => Deferred.done(started, exit))
237
- ) as Effect.Effect<
238
- MachineRef<State, Event, Error, Output, Emitted>,
239
- InitialError,
240
- Requirements | Scope.Scope
241
- >
237
+ )
242
238
  )
243
239
  return {
244
240
  id: options?.id ?? sessionId,
@@ -269,7 +269,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
269
269
  event,
270
270
  this.inspectionSubject,
271
271
  this.causation()
272
- )) as ProcessScope<unknown>["sendTo"],
272
+ )),
273
273
  stopChild: this.childRuntime.stop,
274
274
  failCause: (cause: Cause.Cause<unknown>) => this.failCause(cause),
275
275
  inspectInitial: this.inspector === undefined
@@ -351,7 +351,7 @@ class CompiledProcess implements MachineRef<any, any, any, any> {
351
351
  event,
352
352
  self.inspectionSubject,
353
353
  self.causation()
354
- )) as ProcessScope<unknown>["sendTo"],
354
+ )),
355
355
  stopChild: self.childRuntime.stop,
356
356
  failCause: (cause: Cause.Cause<unknown>) => self.failCause(cause),
357
357
  inspectInitial: self.inspector === undefined
@@ -223,13 +223,11 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced(
223
223
  )
224
224
  const sendToTarget: ProcessScope<Event>["sendTo"] = inspector === undefined
225
225
  ? ((target: unknown, event: unknown) =>
226
- isMachineTarget(target) ? target.send(event) : sendTo(target as ChildSelector, event)) as ProcessScope<
227
- Event
228
- >["sendTo"]
226
+ isMachineTarget(target) ? target.send(event) : sendTo(target as ChildSelector, event))
229
227
  : ((target: unknown, event: unknown) =>
230
228
  isMachineTarget(target)
231
229
  ? sendMachineTarget(target, event, subject, currentCausation())
232
- : sendTo(target as ChildSelector, event, subject, currentCausation())) as ProcessScope<Event>["sendTo"]
230
+ : sendTo(target as ChildSelector, event, subject, currentCausation()))
233
231
 
234
232
  const scope: ProcessScope<Event> = {
235
233
  self,