@typeonce/effect-machine 0.36.0 → 0.38.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 (61) hide show
  1. package/README.md +57 -0
  2. package/dist/Machine.d.ts +30 -0
  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/declaration.d.ts.map +1 -1
  7. package/dist/internal/machine/declaration.js +1 -0
  8. package/dist/internal/machine/declaration.js.map +1 -1
  9. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  10. package/dist/internal/machine/executionPlan.js +4 -2
  11. package/dist/internal/machine/executionPlan.js.map +1 -1
  12. package/dist/internal/machine/invocation.d.ts +1 -0
  13. package/dist/internal/machine/invocation.d.ts.map +1 -1
  14. package/dist/internal/machine/invocation.js +26 -3
  15. package/dist/internal/machine/invocation.js.map +1 -1
  16. package/dist/internal/machine/invocationDefinition.d.ts +3 -1
  17. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  18. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  19. package/dist/internal/machine/machine.d.ts +6 -0
  20. package/dist/internal/machine/machine.d.ts.map +1 -1
  21. package/dist/internal/machine/machine.js +2 -0
  22. package/dist/internal/machine/machine.js.map +1 -1
  23. package/dist/internal/machine/observation.d.ts +3 -0
  24. package/dist/internal/machine/observation.d.ts.map +1 -0
  25. package/dist/internal/machine/observation.js +28 -0
  26. package/dist/internal/machine/observation.js.map +1 -0
  27. package/dist/internal/testing/machine/arbitrary.d.ts +4 -2
  28. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  29. package/dist/internal/testing/machine/arbitrary.js +5 -4
  30. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  31. package/dist/internal/testing/machine/finiteModel.d.ts +2 -2
  32. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  33. package/dist/internal/testing/machine/finiteModel.js +39 -33
  34. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  35. package/dist/internal/testing/machine/referenceModel.d.ts.map +1 -1
  36. package/dist/internal/testing/machine/referenceModel.js +6 -5
  37. package/dist/internal/testing/machine/referenceModel.js.map +1 -1
  38. package/dist/internal/testing/machine/runtime.d.ts +8 -9
  39. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  40. package/dist/internal/testing/machine/runtime.js +16 -14
  41. package/dist/internal/testing/machine/runtime.js.map +1 -1
  42. package/dist/internal/testing/machine/verification.js +7 -7
  43. package/dist/internal/testing/machine/verification.js.map +1 -1
  44. package/dist/testing/MachineTest.d.ts +6 -6
  45. package/dist/testing/MachineTest.d.ts.map +1 -1
  46. package/dist/testing/MachineTest.js +2 -2
  47. package/docs/agent-guide.md +20 -0
  48. package/package.json +4 -4
  49. package/src/Machine.ts +47 -0
  50. package/src/internal/machine/declaration.ts +1 -0
  51. package/src/internal/machine/executionPlan.ts +4 -2
  52. package/src/internal/machine/invocation.ts +34 -3
  53. package/src/internal/machine/invocationDefinition.ts +1 -0
  54. package/src/internal/machine/machine.ts +3 -0
  55. package/src/internal/machine/observation.ts +39 -0
  56. package/src/internal/testing/machine/arbitrary.ts +11 -4
  57. package/src/internal/testing/machine/finiteModel.ts +87 -59
  58. package/src/internal/testing/machine/referenceModel.ts +6 -5
  59. package/src/internal/testing/machine/runtime.ts +24 -22
  60. package/src/internal/testing/machine/verification.ts +13 -13
  61. package/src/testing/MachineTest.ts +6 -6
@@ -474,3 +474,23 @@ const testProgram = Effect.gen(function*() {
474
474
  Use pure planner traces for state and transition rules. Start a live machine
475
475
  and use `MachineTest.probe` when a test depends on timers, invoked work, raised
476
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/effect-machine",
3
- "version": "0.36.0",
3
+ "version": "0.38.0",
4
4
  "description": "Schema-first state machines and statecharts for Effect",
5
5
  "author": "Sandro Maglione",
6
6
  "repository": {
@@ -46,12 +46,12 @@
46
46
  "provenance": true
47
47
  },
48
48
  "peerDependencies": {
49
- "effect": "4.0.0-rc.112"
49
+ "effect": "4.0.0-rc.116"
50
50
  },
51
51
  "devDependencies": {
52
- "@effect/vitest": "4.0.0-rc.112",
52
+ "@effect/vitest": "4.0.0-rc.116",
53
53
  "@types/node": "25.7.0",
54
- "effect": "4.0.0-rc.112",
54
+ "effect": "4.0.0-rc.116",
55
55
  "tinybench": "2.9.0",
56
56
  "tstyche": "7.2.1",
57
57
  "typescript": "6.0.3",
package/src/Machine.ts CHANGED
@@ -9186,6 +9186,53 @@ export const watch: <State, Event, Error = never, Output = never>(
9186
9186
  ref: MachineRef<State, Event, Error, Output>
9187
9187
  ) => Stream.Stream<RuntimeOutcome<State, Error, Output>> = internal.watch
9188
9188
 
9189
+ /**
9190
+ * Waits for the first current or subsequent published snapshot matching a predicate.
9191
+ *
9192
+ * Use for external Effect coordination and tests. Prefer atom selectors for UI
9193
+ * reads, invocation outcomes for workflow behavior, and `ref.join` for output.
9194
+ * This observes state; it does not acknowledge or correlate a sent event.
9195
+ *
9196
+ * The predicate runs before terminal classification, so explicitly matching a
9197
+ * done, error, or stopped snapshot succeeds. Otherwise an error preserves its
9198
+ * Cause, stopping fails with `StoppedError`, and completion without a match
9199
+ * fails with `Cause.NoSuchElementError`. Predicate exceptions are defects.
9200
+ *
9201
+ * Evaluation subscribes lazily. Interruption releases only the subscription,
9202
+ * never the machine. There is no default timeout; compose `Effect.timeout`.
9203
+ * Type predicates narrow the returned snapshot. Intermediate microsteps and
9204
+ * historical snapshots are not observed.
9205
+ *
9206
+ * @example
9207
+ * ```ts
9208
+ * const snapshot = yield* Machine.waitFor(ref, isReady).pipe(Effect.timeout("5 seconds"))
9209
+ * ```
9210
+ * @category combinators
9211
+ * @since 0.37.0
9212
+ */
9213
+ export const waitFor: {
9214
+ <State, Error, Output, Narrowed extends RuntimeSnapshot<State, Error, Output>>(
9215
+ predicate: (snapshot: RuntimeSnapshot<State, Error, Output>) => snapshot is Narrowed
9216
+ ): <Event, Emitted>(ref: MachineRef<State, Event, Error, Output, Emitted>) => Effect.Effect<
9217
+ Narrowed,
9218
+ Error | StoppedError | Cause.NoSuchElementError
9219
+ >
9220
+ <State, Error, Output>(
9221
+ predicate: (snapshot: RuntimeSnapshot<State, Error, Output>) => boolean
9222
+ ): <Event, Emitted>(ref: MachineRef<State, Event, Error, Output, Emitted>) => Effect.Effect<
9223
+ RuntimeSnapshot<State, Error, Output>,
9224
+ Error | StoppedError | Cause.NoSuchElementError
9225
+ >
9226
+ <State, Event, Error, Output, Emitted, Narrowed extends RuntimeSnapshot<State, Error, Output>>(
9227
+ ref: MachineRef<State, Event, Error, Output, Emitted>,
9228
+ predicate: (snapshot: RuntimeSnapshot<State, Error, Output>) => snapshot is Narrowed
9229
+ ): Effect.Effect<Narrowed, Error | StoppedError | Cause.NoSuchElementError>
9230
+ <State, Event, Error, Output, Emitted>(
9231
+ ref: MachineRef<State, Event, Error, Output, Emitted>,
9232
+ predicate: (snapshot: RuntimeSnapshot<State, Error, Output>) => boolean
9233
+ ): Effect.Effect<RuntimeSnapshot<State, Error, Output>, Error | StoppedError | Cause.NoSuchElementError>
9234
+ } = internal.waitFor
9235
+
9189
9236
  /**
9190
9237
  * Prepares a fresh machine without initializing it.
9191
9238
  *
@@ -131,6 +131,7 @@ export const invocation = (
131
131
  const field = { effects: "effect", streams: "stream", timers: "after", logic: "logic" }[source.kind]
132
132
  return {
133
133
  ...rest,
134
+ sourceName: src,
134
135
  id: rest.id ?? src,
135
136
  [field]: !parameterized && (source.kind === "timers" || source.kind === "logic") ? source.value : resolve
136
137
  }
@@ -537,7 +537,8 @@ const normalizeIndexedTargetStateSync = (
537
537
  const targetIndex = isTarget(target) ? descriptor.indexByPath.get(String(target.path)) : undefined
538
538
  if (
539
539
  targetIndex === activeLeafIndex && current.active[activeLeafIndex] === 1 && isTarget(target) &&
540
- target[TargetSnapshotTypeId] === undefined && target.values === undefined && current.completedOrder.length === 0
540
+ target[TargetSnapshotTypeId] === undefined && target.values === undefined && current.completedOrder.length === 0 &&
541
+ descriptor.valued[activeLeafIndex]
541
542
  ) {
542
543
  const values = current.values.slice()
543
544
  values[activeLeafIndex] = decodeStateValueSync(
@@ -863,7 +864,8 @@ const planIndexedFlatState = (
863
864
  ? target[TargetSnapshotTypeId] === undefined && target.values === undefined
864
865
  : !("state" in target) && !("states" in target) && !("completed" in target) && !("history" in target)
865
866
  if (
866
- targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0
867
+ targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0 &&
868
+ descriptor.valued[sourceIndex]
867
869
  ) {
868
870
  updateOwnedIndexedValue(
869
871
  current,
@@ -19,6 +19,7 @@ import { ChildMachineLogicTypeId } from "./symbols.js"
19
19
  /** @internal */
20
20
  export interface AnyConfig {
21
21
  readonly id: string
22
+ readonly sourceName?: string | undefined
22
23
  readonly address?: string
23
24
  readonly descriptor?: ChildMachine.Any
24
25
  readonly src: () => Runtime.ProcessLogic<any, any, any, any, any, any>
@@ -82,6 +83,7 @@ const resolveOne = (
82
83
  if ("effect" in raw) {
83
84
  return {
84
85
  id: String(raw.id),
86
+ sourceName: raw.sourceName,
85
87
  src: () =>
86
88
  oneShot(raw.effect(context) as Effect.Effect<any, any, any>) as unknown as Runtime.ProcessLogic<
87
89
  any,
@@ -100,6 +102,7 @@ const resolveOne = (
100
102
  if ("after" in raw) {
101
103
  return {
102
104
  id: String(raw.id),
105
+ sourceName: raw.sourceName,
103
106
  src: () =>
104
107
  oneShot(Effect.sleep(resolveValue(raw.after, context) as any)) as unknown as Runtime.ProcessLogic<
105
108
  any,
@@ -117,6 +120,7 @@ const resolveOne = (
117
120
  const id = String(raw.id)
118
121
  return {
119
122
  id,
123
+ sourceName: raw.sourceName,
120
124
  src: () =>
121
125
  streamLogic(raw.stream(context), path, id) as unknown as Runtime.ProcessLogic<any, any, any, any, any, any>,
122
126
  onDone: raw.onDone,
@@ -192,11 +196,37 @@ const startResolved = (
192
196
  onDone: unknown,
193
197
  onFailure: unknown,
194
198
  onSnapshot: unknown,
195
- activityKind?: Inspection.Activity["kind"]
199
+ activityKind?: Inspection.Activity["kind"],
200
+ sourceName?: string
196
201
  ): Effect.Effect<void, any, any> =>
197
202
  Effect.suspend(() => {
198
203
  const key = makeKey(path, invokeId)
199
- return ownedChildren.spawn(src, {
204
+ // Source construction keeps its startup failure boundary. Only the hosted
205
+ // program is wrapped; child statecharts retain their execution descriptors.
206
+ const tracedSource = activityKind === undefined ? src : () => {
207
+ const logic = src()
208
+ return {
209
+ ...logic,
210
+ run: (context: Runtime.ProcessContext<any, any>) =>
211
+ Effect.withSpan(
212
+ Effect.suspend(() => logic.run(context)),
213
+ "Machine.invoke",
214
+ {
215
+ attributes: {
216
+ "machine.id": scope.self.id,
217
+ "machine.sessionId": scope.self.sessionId,
218
+ "machine.state.path": path,
219
+ "machine.invoke.id": invokeId,
220
+ "machine.invoke.source": sourceName ?? invokeId,
221
+ "machine.invoke.kind": activityKind,
222
+ "machine.invoke.sessionId": context.self.sessionId
223
+ },
224
+ captureStackTrace: false
225
+ }
226
+ )
227
+ }
228
+ }
229
+ return ownedChildren.spawn(tracedSource, {
200
230
  key,
201
231
  path,
202
232
  id: childId,
@@ -260,7 +290,8 @@ const start = (
260
290
  config.onDone,
261
291
  config.onFailure,
262
292
  config.onSnapshot,
263
- config.activityKind
293
+ config.activityKind,
294
+ config.sourceName
264
295
  )
265
296
  }
266
297
 
@@ -16,6 +16,7 @@ interface Outcomes {
16
16
 
17
17
  export type InvocationDefinition =
18
18
  & Outcomes
19
+ & { readonly sourceName?: string }
19
20
  & (
20
21
  | { readonly id: string; readonly effect: (context: Context) => Effect.Effect<unknown, unknown, unknown> }
21
22
  | { readonly id: string; readonly stream: (context: Context) => Stream.Stream<unknown, unknown, unknown> }
@@ -34,6 +34,7 @@ import type { ChildAlreadyExistsError, InfiniteTransitionError, StartupError } f
34
34
  import type { CapturedStateConfig } from "./implementation.js"
35
35
  import * as InitialDeclaration from "./initialDeclaration.js"
36
36
  import * as InvocationDefinition from "./invocationDefinition.js"
37
+ import * as Observation from "./observation.js"
37
38
  import * as internalPlanner from "./planner.js"
38
39
  import * as internalProcess from "./process.js"
39
40
  import * as Protocol from "./protocol.js"
@@ -1411,6 +1412,8 @@ export const watch = <State, Event, Error = never, Output = never>(
1411
1412
  ref: MachineRef<State, Event, Error, Output>
1412
1413
  ): Stream.Stream<RuntimeOutcome<State, Error, Output>> => internalRuntime.watch(ref)
1413
1414
 
1415
+ export const waitFor = Observation.waitFor
1416
+
1414
1417
  export const prepare = internalProcess.prepare
1415
1418
 
1416
1419
  export const start: <
@@ -0,0 +1,39 @@
1
+ /** Observation of current and subsequent published runtime snapshots. */
2
+ import * as Cause from "effect/Cause"
3
+ import * as Effect from "effect/Effect"
4
+ import { dual } from "effect/Function"
5
+ import * as Option from "effect/Option"
6
+ import * as Stream from "effect/Stream"
7
+ import type * as Machine from "../../Machine.js"
8
+ import { StoppedError } from "./errors.js"
9
+
10
+ export const waitFor: typeof Machine.waitFor = dual(2, <State, Event, Error, Output, Emitted>(
11
+ ref: Machine.MachineRef<State, Event, Error, Output, Emitted>,
12
+ predicate: (snapshot: Machine.RuntimeSnapshot<State, Error, Output>) => boolean
13
+ ): Effect.Effect<Machine.RuntimeSnapshot<State, Error, Output>, Error | StoppedError | Cause.NoSuchElementError> =>
14
+ Effect.suspend(() => {
15
+ let result = Option.none<Machine.RuntimeSnapshot<State, Error, Output>>()
16
+ const absent = () => new Cause.NoSuchElementError(`Machine "${ref.id}" ended without a matching snapshot`)
17
+ return Stream.runForEachWhile(
18
+ ref.changes,
19
+ (snapshot) =>
20
+ Effect.suspend((): Effect.Effect<boolean, Error | StoppedError | Cause.NoSuchElementError> => {
21
+ if (predicate(snapshot)) {
22
+ result = Option.some(snapshot)
23
+ return Effect.succeed(false)
24
+ }
25
+ switch (snapshot.status) {
26
+ case "active":
27
+ return Effect.succeed(true)
28
+ case "error":
29
+ return Effect.failCause(snapshot.cause)
30
+ case "stopped":
31
+ return Effect.fail(new StoppedError())
32
+ case "done":
33
+ return Effect.fail(absent())
34
+ }
35
+ })
36
+ ).pipe(
37
+ Effect.flatMap(() => Option.isSome(result) ? Effect.succeed(result.value) : Effect.fail(absent()))
38
+ )
39
+ }))
@@ -1,6 +1,6 @@
1
1
  import * as Schema from "effect/Schema"
2
2
  import * as SchemaAST from "effect/SchemaAST"
3
- import { FastCheck } from "effect/testing"
3
+ import * as Arbitrary from "effect/unstable/arbitrary/Arbitrary"
4
4
 
5
5
  /**
6
6
  * Warning emitted when schema arbitrary generation must enforce an opaque
@@ -39,8 +39,7 @@ const reportChecks = (
39
39
  path: ReadonlyArray<PropertyKey>
40
40
  ): void => {
41
41
  const visit = (check: SchemaAST.Check<unknown>, covered: boolean): void => {
42
- const arbitrary = check.annotations?.arbitrary
43
- const nextCovered = covered || arbitrary?.constraint !== undefined || arbitrary?.candidate !== undefined
42
+ const nextCovered = covered || check.annotations?.arbitraryConstraint !== undefined
44
43
  if (check._tag !== "Filter") {
45
44
  for (const child of check.checks) visit(child, nextCovered)
46
45
  } else if (!nextCovered) {
@@ -97,6 +96,14 @@ const reportFor = (ast: SchemaAST.AST): SchemaArbitraryReport => {
97
96
 
98
97
  /** @internal */
99
98
  export const toArbitraryWithReport = <S extends Schema.Constraint>(schema: S) => ({
100
- value: Schema.toArbitrary(schema)(FastCheck),
99
+ value: Arbitrary.schema(schema),
101
100
  report: reportFor(schema.ast)
102
101
  })
102
+
103
+ /** Selects one of the supplied generators without replacing its shrink tree. @internal */
104
+ export const chooseArbitrary = <A>(
105
+ ...choices: readonly [Arbitrary.Arbitrary<A>, ...Array<Arbitrary.Arbitrary<A>>]
106
+ ): Arbitrary.Arbitrary<A> =>
107
+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: choices.length - 1 }))).pipe(
108
+ Arbitrary.flatMap((index) => choices[index]!)
109
+ )
@@ -10,8 +10,9 @@
10
10
  */
11
11
 
12
12
  import * as Schema from "effect/Schema"
13
- import { FastCheck } from "effect/testing"
13
+ import * as Arbitrary from "effect/unstable/arbitrary/Arbitrary"
14
14
  import * as Machine from "../../../Machine.js"
15
+ import { chooseArbitrary } from "./arbitrary.js"
15
16
 
16
17
  /**
17
18
  * An atomic state in a finite generated model.
@@ -307,7 +308,7 @@ export interface FiniteModelDiagnostics {
307
308
  * @since 0.4.0
308
309
  */
309
310
  export interface FiniteModels {
310
- readonly arbitrary: FastCheck.Arbitrary<FiniteModel>
311
+ readonly arbitrary: Arbitrary.Arbitrary<FiniteModel>
311
312
  readonly diagnostics: FiniteModelDiagnostics
312
313
  }
313
314
 
@@ -397,26 +398,32 @@ const resolveOptions = (options: FiniteModelOptions): FiniteModelDiagnostics["li
397
398
  const rawStateArbitrary = (
398
399
  depth: number,
399
400
  limits: FiniteModelDiagnostics["limits"]
400
- ): FastCheck.Arbitrary<RawState> => {
401
- const leaf = FastCheck.boolean().map((final): RawState => final ? { _tag: "Final" } : { _tag: "Atomic" })
401
+ ): Arbitrary.Arbitrary<RawState> => {
402
+ const leaf = Arbitrary.schema(Schema.Boolean).pipe(
403
+ Arbitrary.map((final): RawState => final ? { _tag: "Final" } : { _tag: "Atomic" })
404
+ )
402
405
  if (depth >= limits.maxDepth) return leaf
403
406
 
404
407
  const nested = rawStateArbitrary(depth + 1, limits)
405
- const compound = FastCheck.array(nested, {
408
+ const compound = Arbitrary.array(nested, {
406
409
  minLength: 1,
407
410
  maxLength: limits.maxChildren
408
- }).chain((states) =>
409
- FastCheck.integer({ min: 0, max: states.length - 1 }).map((initialIndex): RawCompoundState => ({
410
- _tag: "Compound",
411
- initialIndex,
412
- states
413
- }))
411
+ }).pipe(
412
+ Arbitrary.flatMap((states) =>
413
+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: states.length - 1 }))).pipe(
414
+ Arbitrary.map((initialIndex): RawCompoundState => ({
415
+ _tag: "Compound",
416
+ initialIndex,
417
+ states
418
+ }))
419
+ )
420
+ )
414
421
  )
415
- const parallel = FastCheck.array(nested, {
422
+ const parallel = Arbitrary.array(nested, {
416
423
  minLength: 2,
417
424
  maxLength: limits.maxParallelRegions
418
- }).map((states): RawParallelState => ({ _tag: "Parallel", states }))
419
- return FastCheck.oneof(leaf, compound, parallel)
425
+ }).pipe(Arbitrary.map((states): RawParallelState => ({ _tag: "Parallel", states })))
426
+ return chooseArbitrary(leaf, compound, parallel)
420
427
  }
421
428
 
422
429
  const normalizeStates = (raw: ReadonlyArray<RawState>): ReadonlyArray<FiniteState> => {
@@ -659,7 +666,7 @@ const makeTransitionArbitrary = (
659
666
  events: ReadonlyArray<string>,
660
667
  maxTransitions: number,
661
668
  historyScenarios: ReadonlyArray<FiniteHistoryScenario> = []
662
- ): FastCheck.Arbitrary<ReadonlyArray<FiniteTransition>> => {
669
+ ): Arbitrary.Arbitrary<ReadonlyArray<FiniteTransition>> => {
663
670
  const states = flattenStates(roots)
664
671
  const sourceOrder = new Map(states.map((state, index) => [state.path, index]))
665
672
  const stateByPath = new Map(states.map((state) => [state.path, state]))
@@ -773,46 +780,63 @@ const makeTransitionArbitrary = (
773
780
  const materialize = (
774
781
  selected: ReadonlyArray<TransitionCandidate>,
775
782
  allowTargetlessEvents = true
776
- ): FastCheck.Arbitrary<ReadonlyArray<FiniteTransition>> => {
777
- if (selected.length === 0) return FastCheck.constant([])
783
+ ): Arbitrary.Arbitrary<ReadonlyArray<FiniteTransition>> => {
784
+ if (selected.length === 0) return Arbitrary.Constant([])
778
785
  const decisions = selected.map((candidate) =>
779
- FastCheck.record({
786
+ Arbitrary.all({
780
787
  // Targetless event transitions remain useful witnesses. Generated
781
788
  // automatic transitions always exit their source so stabilization is
782
789
  // acyclic by construction; targetless automatic semantics are covered
783
790
  // by focused examples rather than mixed into the finite-model oracle.
784
- targetIndex: FastCheck.integer({
785
- min: candidate.trigger.type === "event" && allowTargetlessEvents ? 0 : 1,
786
- max: candidate.targets.length
787
- }),
788
- targetValueOffset: FastCheck.integer({ min: 0, max: 2 }),
789
- reenter: FastCheck.boolean()
791
+ targetIndex: Arbitrary.schema(
792
+ Schema.Int.check(
793
+ Schema.isBetween({
794
+ minimum: candidate.trigger.type === "event" && allowTargetlessEvents ? 0 : 1,
795
+ maximum: candidate.targets.length
796
+ })
797
+ )
798
+ ),
799
+ targetValueOffset: Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 }))),
800
+ reenter: Arbitrary.schema(Schema.Boolean)
790
801
  })
791
802
  )
792
- return FastCheck.tuple(...decisions).map((values) =>
793
- selected.map((candidate, index): FiniteTransition => {
794
- const decision = values[index]!
795
- const target = decision.targetIndex === 0 ? undefined : candidate.targets[decision.targetIndex - 1]
796
- const targetState = target === undefined ? undefined : states.find(({ path }) => path === target)
797
- const targetValue = targetState?.node._tag === "Atomic" &&
798
- decision.targetValueOffset !== 0
799
- ? targetState.node.value + decision.targetValueOffset
800
- : undefined
801
- const targetFields = target === undefined
802
- ? {}
803
- : { target, ...(targetValue === undefined ? {} : { targetValue }) }
804
- const trigger = candidate.trigger
805
- return trigger.type === "event"
806
- ? { source: candidate.source, trigger, reenter: decision.reenter, ...targetFields }
807
- : { source: candidate.source, trigger, ...targetFields }
808
- })
803
+ return Arbitrary.all([...decisions]).pipe(
804
+ Arbitrary.map((values) =>
805
+ selected.map((candidate, index): FiniteTransition => {
806
+ const decision = values[index]!
807
+ const target = decision.targetIndex === 0 ? undefined : candidate.targets[decision.targetIndex - 1]
808
+ const targetState = target === undefined ? undefined : states.find(({ path }) => path === target)
809
+ const targetValue = targetState?.node._tag === "Atomic" &&
810
+ decision.targetValueOffset !== 0
811
+ ? targetState.node.value + decision.targetValueOffset
812
+ : undefined
813
+ const targetFields = target === undefined
814
+ ? {}
815
+ : { target, ...(targetValue === undefined ? {} : { targetValue }) }
816
+ const trigger = candidate.trigger
817
+ return trigger.type === "event"
818
+ ? { source: candidate.source, trigger, reenter: decision.reenter, ...targetFields }
819
+ : { source: candidate.source, trigger, ...targetFields }
820
+ })
821
+ )
809
822
  )
810
823
  }
811
824
  const optionalBudget = maxTransitions - mandatory.length
812
- const general = FastCheck.subarray([...eventCandidates, ...automaticCandidates], {
813
- minLength: 0,
814
- maxLength: Math.min(optionalBudget, eventCandidates.length + automaticCandidates.length)
815
- }).chain((selected) => materialize(selected).map((transitions) => orderTransitions([...mandatory, ...transitions])))
825
+ const candidates = [...eventCandidates, ...automaticCandidates]
826
+ const selectedCandidates = candidates.length === 0
827
+ ? Arbitrary.Constant<ReadonlyArray<TransitionCandidate>>([])
828
+ : Arbitrary.schema(
829
+ Schema.Array(
830
+ Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: candidates.length - 1 }))
831
+ ).check(Schema.isUnique(), Schema.isMaxLength(Math.min(optionalBudget, candidates.length)))
832
+ ).pipe(
833
+ Arbitrary.map((indices) => [...indices].sort((a, b) => a - b).map((index) => candidates[index]!))
834
+ )
835
+ const general = selectedCandidates.pipe(
836
+ Arbitrary.flatMap((selected) =>
837
+ materialize(selected).pipe(Arbitrary.map((transitions) => orderTransitions([...mandatory, ...transitions])))
838
+ )
839
+ )
816
840
 
817
841
  if (mandatory.length > 0 || optionalBudget < 2 || automaticCandidates.length === 0) return general
818
842
 
@@ -836,10 +860,14 @@ const makeTransitionArbitrary = (
836
860
  })
837
861
  if (chainCandidates.length === 0) return general
838
862
 
839
- const chain = FastCheck.constantFrom(...chainCandidates).chain(({ automatic, event }) =>
840
- materialize([event, automatic], false).map((transitions) => orderTransitions(transitions))
863
+ const chain = Arbitrary.schema(
864
+ Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: chainCandidates.length - 1 }))
865
+ ).pipe(Arbitrary.map((index) => chainCandidates[index]!)).pipe(
866
+ Arbitrary.flatMap(({ automatic, event }) =>
867
+ materialize([event, automatic], false).pipe(Arbitrary.map((transitions) => orderTransitions(transitions)))
868
+ )
841
869
  )
842
- return FastCheck.oneof(general, chain)
870
+ return chooseArbitrary(general, chain)
843
871
  }
844
872
 
845
873
  /**
@@ -858,20 +886,20 @@ const makeTransitionArbitrary = (
858
886
  */
859
887
  export const finiteModels = (options: FiniteModelOptions = {}): FiniteModels => {
860
888
  const limits = resolveOptions(options)
861
- const rawRoots = FastCheck.array(rawStateArbitrary(1, limits), {
889
+ const rawRoots = Arbitrary.array(rawStateArbitrary(1, limits), {
862
890
  minLength: 1,
863
891
  maxLength: limits.maxRoots
864
892
  })
865
- const arbitrary = rawRoots.chain((raw) => {
893
+ const arbitrary = rawRoots.pipe(Arbitrary.flatMap((raw) => {
866
894
  const activeRoots = normalizeStates(raw)
867
- return FastCheck.tuple(
868
- FastCheck.integer({ min: 0, max: activeRoots.length - 1 }),
869
- FastCheck.integer({ min: 1, max: limits.maxEvents }),
870
- FastCheck.array(FastCheck.constantFrom("shallow" as const, "deep" as const), {
895
+ return Arbitrary.all([
896
+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: activeRoots.length - 1 }))),
897
+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: limits.maxEvents }))),
898
+ Arbitrary.array(Arbitrary.schema(Schema.Literals(["shallow" as const, "deep" as const])), {
871
899
  minLength: 0,
872
900
  maxLength: limits.maxHistoryStates
873
901
  })
874
- ).chain(([initialIndex, eventCount, historyDecisions]) => {
902
+ ]).pipe(Arbitrary.flatMap(([initialIndex, eventCount, historyDecisions]) => {
875
903
  const events = Array.from({ length: eventCount }, (_, index) => `Event${index}`)
876
904
  const initial = activeRoots[initialIndex]!.key
877
905
  const generated = addGeneratedHistory(
@@ -885,11 +913,11 @@ export const finiteModels = (options: FiniteModelOptions = {}): FiniteModels =>
885
913
  const roots = generated.scenarios.length === 0
886
914
  ? addGeneratedChoices(generated.roots, limits.maxChoiceStates)
887
915
  : generated.roots
888
- return makeTransitionArbitrary(roots, initial, events, limits.maxTransitions, generated.scenarios).map(
889
- (transitions) => freezeModel(roots, initial, events, transitions, generated.scenarios)
916
+ return makeTransitionArbitrary(roots, initial, events, limits.maxTransitions, generated.scenarios).pipe(
917
+ Arbitrary.map((transitions) => freezeModel(roots, initial, events, transitions, generated.scenarios))
890
918
  )
891
- })
892
- })
919
+ }))
920
+ }))
893
921
 
894
922
  return {
895
923
  arbitrary,
@@ -970,12 +970,13 @@ const evaluateTransition = (
970
970
  if (!changed) {
971
971
  return { ...selection, next, targetPath, changed, exitPaths: [], entryPaths: [] }
972
972
  }
973
- const naturalBoundary = targetPath === undefined
974
- ? getState(index, transition.source).parent
975
- : leastCommonAncestor(index, selection.leaf, targetPath)
976
973
  const choiceEntry = transition.target === undefined ? undefined : entryChoicePath(index, transition.target)
977
- const choiceResolvesToActiveAncestor = choiceEntry !== undefined &&
978
- isPathInSubtree(transition.source, resolveChoicePath(index, choiceEntry))
974
+ const lifecycleTarget = choiceEntry === undefined ? targetPath : choiceChainResolvedTargetPath(index, choiceEntry)
975
+ const naturalBoundary = lifecycleTarget === undefined
976
+ ? getState(index, transition.source).parent
977
+ : leastCommonAncestor(index, selection.leaf, lifecycleTarget)
978
+ const choiceResolvesToActiveAncestor = choiceEntry !== undefined && lifecycleTarget !== undefined &&
979
+ isPathInSubtree(transition.source, lifecycleTarget)
979
980
  const boundary = reenters(transition)
980
981
  ? !choiceResolvesToActiveAncestor
981
982
  ? broadenBoundary(index, naturalBoundary, getState(index, transition.source).parent)