deltafold 0.1.0 → 0.2.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 (50) hide show
  1. package/README.md +96 -1
  2. package/dist/changelog.d.ts +10 -10
  3. package/dist/changelog.js +4 -4
  4. package/dist/changelog.js.map +1 -1
  5. package/dist/{document-BZcZo9nr.js → document-HfPyYxEd.js} +20 -20
  6. package/dist/{document-BZcZo9nr.js.map → document-HfPyYxEd.js.map} +1 -1
  7. package/dist/{document-DWHsgywm.d.ts → document-gtXeGFJR.d.ts} +41 -41
  8. package/dist/{document-DWHsgywm.d.ts.map → document-gtXeGFJR.d.ts.map} +1 -1
  9. package/dist/html.d.ts +2 -2
  10. package/dist/html.js +2 -2
  11. package/dist/html.js.map +1 -1
  12. package/dist/index.d.ts +681 -102
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +908 -235
  15. package/dist/index.js.map +1 -1
  16. package/dist/markdown.d.ts +2 -2
  17. package/dist/markdown.js +2 -2
  18. package/dist/markdown.js.map +1 -1
  19. package/dist/{mdast-DiRsYwPU.js → mdast-Oqkh0Gs1.js} +2 -2
  20. package/dist/{mdast-DiRsYwPU.js.map → mdast-Oqkh0Gs1.js.map} +1 -1
  21. package/dist/{package-BfBYnaCz.d.ts → package-CA5R57IC.d.ts} +117 -112
  22. package/dist/{package-BfBYnaCz.d.ts.map → package-CA5R57IC.d.ts.map} +1 -1
  23. package/package.json +3 -3
  24. package/src/features/documents/changelog.ts +8 -8
  25. package/src/features/documents/document.ts +39 -39
  26. package/src/features/documents/index.ts +2 -2
  27. package/src/features/execution/executor.ts +631 -272
  28. package/src/features/execution/handler.ts +205 -84
  29. package/src/features/execution/interaction.ts +174 -0
  30. package/src/features/execution/observation.ts +489 -0
  31. package/src/features/execution/observer.ts +395 -0
  32. package/src/features/execution/promise-callback.ts +76 -0
  33. package/src/features/package.ts +3 -3
  34. package/src/features/planning/history.ts +10 -10
  35. package/src/features/planning/identifiers.ts +7 -4
  36. package/src/features/planning/resolve-error.ts +13 -13
  37. package/src/features/planning/resolve.ts +11 -4
  38. package/src/features/planning/rewrite.ts +1 -1
  39. package/src/features/planning/validate.ts +1 -1
  40. package/src/foundation/action.ts +17 -17
  41. package/src/foundation/change.ts +10 -10
  42. package/src/foundation/instruction.ts +5 -5
  43. package/src/foundation/migration.ts +12 -12
  44. package/src/foundation/plan.ts +23 -18
  45. package/src/foundation/rule.ts +6 -6
  46. package/src/foundation/shortcut.ts +6 -6
  47. package/src/foundation/version.ts +6 -6
  48. package/src/index.ts +15 -11
  49. package/src/renderers/html.ts +1 -1
  50. package/src/renderers/markdown.ts +1 -1
@@ -17,16 +17,31 @@ import type * as Action from "../../foundation/action.ts";
17
17
  import type * as Plan from "../../foundation/plan.ts";
18
18
  import type { Node, Occurrence } from "../../foundation/plan.ts";
19
19
  import * as Handler from "./handler.ts";
20
+ import type * as Interaction from "./interaction.ts";
21
+ import { makeEmitter, type Emitter } from "./observation.ts";
22
+ import type * as Observer from "./observer.ts";
20
23
  import { SettlementReference } from "./settlement.ts";
21
24
 
22
25
  /**
23
26
  * What happened to one occurrence, or what a dry run predicts.
24
27
  *
25
- * @since @next
28
+ * @since 0.0.1
26
29
  */
27
30
  export type Outcome<E = unknown> =
28
- | { readonly _tag: "Completed" }
31
+ | { readonly _tag: "Completed"; readonly performer: "automated" }
32
+ | {
33
+ readonly _tag: "Completed";
34
+ readonly performer: "manual";
35
+ /**
36
+ * What supports completion. `asserted`: the person said so and nothing checked
37
+ * it. `verified`: the person said so and the handler's `verify` check passed.
38
+ * Neither proves how the work was done.
39
+ */
40
+ readonly confirmation: "asserted" | "verified";
41
+ }
29
42
  | { readonly _tag: "Skipped"; readonly reason: string }
43
+ /** The person asked to confirm manual work answered that it is not done. */
44
+ | { readonly _tag: "Declined" }
30
45
  | {
31
46
  readonly _tag: "Failed";
32
47
  readonly phase: Handler.Phase;
@@ -48,23 +63,35 @@ export type Outcome<E = unknown> =
48
63
  }
49
64
  /** Not started because execution stopped first. */
50
65
  | { readonly _tag: "Unattempted" }
51
- /** `evaluated`: whether a prepare phase ran and decided to apply. */
52
- | { readonly _tag: "WouldExecute"; readonly evaluated: boolean }
66
+ /**
67
+ * `evaluated`: whether a prepare phase ran and decided to apply. A `manual` occurrence
68
+ * would wait for a person; a dry run never asks.
69
+ */
70
+ | {
71
+ readonly _tag: "WouldExecute";
72
+ readonly evaluated: boolean;
73
+ readonly performer: Handler.Performer;
74
+ }
53
75
  | { readonly _tag: "WouldSkip"; readonly reason: string }
54
- | { readonly _tag: "Undetermined"; readonly reason: string }
76
+ | {
77
+ readonly _tag: "Undetermined";
78
+ readonly reason: string;
79
+ /** A `manual` occurrence would wait for a person if it executes. */
80
+ readonly performer: Handler.Performer;
81
+ }
55
82
  | {
56
83
  readonly _tag: "PreparationFailed";
57
84
  readonly error: E | undefined;
58
85
  readonly cause: Cause.Cause<E>;
59
86
  };
60
87
 
61
- /** @since @next */
88
+ /** @since 0.0.1 */
62
89
  export type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {
63
90
  readonly occurrence: Occurrence<A>;
64
91
  readonly outcome: Outcome<E>;
65
92
  };
66
93
 
67
- /** @since @next */
94
+ /** @since 0.0.1 */
68
95
  export type Report<A extends Action.Any = Action.Any, E = unknown> = {
69
96
  readonly _tag: "Report";
70
97
  readonly mode: "execute" | "dry-run";
@@ -81,18 +108,20 @@ export type Report<A extends Action.Any = Action.Any, E = unknown> = {
81
108
  /** Every occurrence in plan order. */
82
109
  readonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;
83
110
  /**
84
- * Whether any apply phase started. A started apply phase may have partially changed
85
- * state.
111
+ * Whether any apply phase started or any person was asked to do manual work. Either
112
+ * may have partially changed state.
86
113
  */
87
114
  readonly bodiesStarted: boolean;
88
115
  /** Progress is not persisted. Rerunning the plan repeats completed actions. */
89
116
  readonly persistence: "none";
117
+ /** Observers that failed or were abandoned. Never affects outcomes or status. */
118
+ readonly observation: ReadonlyArray<Observer.ObservationFailure>;
90
119
  };
91
120
 
92
121
  /**
93
122
  * A handler is missing, duplicated, or bound to a different definition.
94
123
  *
95
- * @since @next
124
+ * @since 0.0.1
96
125
  */
97
126
  export type CoverageIssue = {
98
127
  readonly _tag: "Missing" | "Duplicate" | "Mismatched";
@@ -117,7 +146,7 @@ const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
117
146
  * For an occurrence that a rule produced, the issue names the rule and the occurrences
118
147
  * it replaced.
119
148
  *
120
- * @since @next
149
+ * @since 0.0.1
121
150
  */
122
151
  export class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{
123
152
  readonly issues: ReadonlyArray<CoverageIssue>;
@@ -133,24 +162,69 @@ export class HandlerCoverageError<A extends Action.Any = Action.Any> extends Han
133
162
  }
134
163
  }
135
164
 
165
+ const InteractionUnavailableBase = Data.TaggedError("InteractionUnavailable");
166
+
167
+ /**
168
+ * The plan has manual handlers, and the run has no `interaction` to ask a person. The
169
+ * run fails before any handler phase or prompt.
170
+ *
171
+ * @since 0.2.0
172
+ */
173
+ export class InteractionUnavailable<
174
+ A extends Action.Any = Action.Any,
175
+ > extends InteractionUnavailableBase<{
176
+ /** The occurrences that a manual handler covers, in plan order. */
177
+ readonly occurrences: ReadonlyArray<Occurrence<A>>;
178
+ readonly report: Report<A, never>;
179
+ }> {
180
+ override get message() {
181
+ return `No interaction is available to confirm manual work for ${this.occurrences
182
+ .map((occurrence) => `"${occurrence.id}" (${occurrence.action.description})`)
183
+ .join(
184
+ ", ",
185
+ )}. Supply the \`interaction\` option, or bind automated handlers to these actions.`;
186
+ }
187
+ }
188
+
189
+ const listIds = (entries: ReadonlyArray<OccurrenceReport>) =>
190
+ entries
191
+ .map((entry) =>
192
+ entry.outcome._tag === "Failed"
193
+ ? `"${entry.occurrence.id}" (${entry.outcome.phase})`
194
+ : `"${entry.occurrence.id}"`,
195
+ )
196
+ .join(", ");
197
+
136
198
  const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
137
199
 
138
200
  /**
139
- * An occurrence failed. Execution stopped admitting new actions; started ones settled.
201
+ * An occurrence failed, or a person declined manual work. Execution stopped admitting
202
+ * new actions; started ones settled.
140
203
  *
141
- * @since @next
204
+ * @since 0.0.1
142
205
  */
143
206
  export class ExecutionFailed<
144
207
  A extends Action.Any = Action.Any,
145
208
  E = unknown,
146
209
  > extends ExecutionFailedBase<{
147
210
  readonly failures: ReadonlyArray<OccurrenceReport<A, E>>;
211
+ /** Manual occurrences that a person declined. */
212
+ readonly declined: ReadonlyArray<OccurrenceReport<A, E>>;
148
213
  readonly report: Report<A, E>;
149
214
  }> {
150
215
  override get message() {
151
- return `Execution failed at ${this.failures
152
- .map((failure) => `"${failure.occurrence.id}"`)
153
- .join(", ")}. Completed actions were not rolled back.`;
216
+ const parts = [
217
+ ...(this.failures.length === 0
218
+ ? []
219
+ : [`Execution failed at ${listIds(this.failures)}.`]),
220
+ ...(this.declined.length === 0
221
+ ? []
222
+ : [
223
+ `Manual work was declined at ${listIds(this.declined)}, which stopped the run.`,
224
+ ]),
225
+ ];
226
+
227
+ return `${parts.join(" ")} Completed actions were not rolled back.`;
154
228
  }
155
229
  }
156
230
 
@@ -160,7 +234,7 @@ const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
160
234
  * Why an execution or an occurrence was interrupted: explicit cancellation, a configured
161
235
  * timeout, or an Effect handler that interrupted itself.
162
236
  *
163
- * @since @next
237
+ * @since 0.0.1
164
238
  */
165
239
  export type InterruptReason = "cancelled" | "timeout" | "handler";
166
240
 
@@ -174,7 +248,7 @@ const interruptedBy: Record<InterruptReason, string> = {
174
248
  * Explicit cancellation, a configured timeout, or a handler's own interruption stopped
175
249
  * execution.
176
250
  *
177
- * @since @next
251
+ * @since 0.0.1
178
252
  */
179
253
  export class ExecutionInterrupted<
180
254
  A extends Action.Any = Action.Any,
@@ -196,9 +270,10 @@ export class ExecutionInterrupted<
196
270
  }
197
271
  }
198
272
 
199
- /** @since @next */
273
+ /** @since 0.0.1 */
200
274
  export type ExecutionError<A extends Action.Any, E> =
201
275
  | HandlerCoverageError<A>
276
+ | InteractionUnavailable<A>
202
277
  | ExecutionFailed<A, E>
203
278
  | ExecutionInterrupted<A, E>;
204
279
 
@@ -206,7 +281,7 @@ export type ExecutionError<A extends Action.Any, E> =
206
281
  * Action identifiers of a statically covered plan that no handler in the array
207
282
  * implements.
208
283
  *
209
- * @since @next
284
+ * @since 0.0.1
210
285
  */
211
286
  export type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = "runtime" extends C
212
287
  ? never
@@ -228,20 +303,42 @@ type CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [
228
303
  /**
229
304
  * Errors an execution can report for its occurrences.
230
305
  *
231
- * @since @next
306
+ * @since 0.0.1
232
307
  */
233
- export type Errors<H> = Handler.Error<H>;
308
+ export type Errors<H, I = never> = Handler.Error<H> | Interaction.Error<I>;
234
309
 
235
310
  /**
236
- * Effect services an execution requires: the services of its handlers.
311
+ * Effect services an execution requires: the services of its handlers, its
312
+ * interaction, and its observers.
237
313
  *
238
- * @since @next
314
+ * @since 0.0.1
239
315
  */
240
- export type Requirements<H> = Handler.Services<H>;
241
-
242
- /** @since @next */
243
- export type Options<H extends Handler.Any> = {
316
+ export type Requirements<H, I = never, O = never> =
317
+ | Handler.Services<H>
318
+ | Interaction.Services<I>
319
+ | Observer.Services<O>;
320
+
321
+ /** @since 0.0.1 */
322
+ export type Options<
323
+ H extends Handler.Any,
324
+ I extends Interaction.Any = never,
325
+ O extends Observer.Any = never,
326
+ > = {
244
327
  readonly handlers?: ReadonlyArray<H>;
328
+ /**
329
+ * Asks a person to confirm the work of manual handlers. A run whose plan has manual
330
+ * handlers fails with `InteractionUnavailable` before it starts when this is absent.
331
+ * A dry run never asks and does not need it.
332
+ */
333
+ readonly interaction?: I;
334
+ /**
335
+ * Receive the run's events, in array order. The executor waits for each observer
336
+ * before it continues; an observer failure is recorded in `report.observation` and never changes
337
+ * the outcome.
338
+ */
339
+ readonly observers?: ReadonlyArray<O>;
340
+ /** Identifies the run in observer events. */
341
+ readonly runId?: string;
245
342
  /**
246
343
  * Run prepare phases without running any apply phase. A prepare phase that may
247
344
  * depend on an earlier action is reported `Undetermined`, because the dry run does
@@ -250,8 +347,10 @@ export type Options<H extends Handler.Any> = {
250
347
  readonly dryRun?: boolean;
251
348
  /**
252
349
  * Limit for each phase of an occurrence: the prepare phase and the apply phase each
253
- * get the full limit. Exceeding it interrupts that action and stops admitting new
254
- * ones. It applies to dry-run prepare phases too.
350
+ * get the full limit, and so does the verification of manual work. Exceeding it
351
+ * interrupts that action and stops admitting new ones. It applies to dry-run prepare
352
+ * phases too. It never limits the wait for a person to confirm manual work; cancel
353
+ * the run to end that wait.
255
354
  */
256
355
  readonly timeout?: Duration.Input;
257
356
  /**
@@ -323,6 +422,7 @@ const report = <A extends Action.Any, E>(
323
422
  status: Report["status"],
324
423
  outcomes: ReadonlyMap<string, Outcome<E>>,
325
424
  bodiesStarted: boolean,
425
+ observation: ReadonlyArray<Observer.ObservationFailure> = [],
326
426
  ): Report<A, E> => ({
327
427
  _tag: "Report",
328
428
  mode,
@@ -336,6 +436,7 @@ const report = <A extends Action.Any, E>(
336
436
  })),
337
437
  bodiesStarted,
338
438
  persistence: "none",
439
+ observation: [...observation],
339
440
  });
340
441
 
341
442
  const failureOf = <E>(cause: Cause.Cause<E>) => ({
@@ -383,6 +484,9 @@ type PhaseResult<T, E> =
383
484
 
384
485
  type ControlOptions = Pick<Options<never>, "timeout" | "settleTimeout">;
385
486
 
487
+ /** Waiting for a person is `untimed`: only cancellation ends it. */
488
+ type Timing = "timed" | "untimed";
489
+
386
490
  /**
387
491
  * Logs a cleanup failure that the report cannot carry, with the occurrence or the
388
492
  * services layer that owned the resources.
@@ -395,12 +499,20 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
395
499
  Effect.gen(function* () {
396
500
  const halt: { reason: StopReason | undefined } = { reason: undefined };
397
501
  const cancelled = yield* Deferred.make<"cancelled">();
502
+ /** Completes on cancellation or a timeout. Observer deliveries are bounded from then on. */
503
+ const stopped = yield* Deferred.make<void>();
398
504
  const settleTimeout = options.settleTimeout ?? Duration.seconds(5);
399
505
 
400
506
  const stop = (reason: StopReason) => {
401
507
  halt.reason ??= reason;
508
+ if (reason === "cancelled" || reason === "timeout") {
509
+ Deferred.doneUnsafe(stopped, Exit.void);
510
+ }
402
511
  };
512
+ // A failure can be the first stop reason, so cancellation is also tracked on its own.
513
+ let cancellationArrived = false;
403
514
  subscribe?.(() => {
515
+ cancellationArrived = true;
404
516
  stop("cancelled");
405
517
  Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
406
518
  });
@@ -412,6 +524,7 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
412
524
  const runPhase = <T, E, R>(
413
525
  work: Effect.Effect<T, E, R>,
414
526
  unsettled: Array<Promise<void>>,
527
+ timing: Timing = "timed",
415
528
  ): Effect.Effect<PhaseResult<T, E>, never, R> =>
416
529
  Effect.gen(function* () {
417
530
  let settled = true;
@@ -427,7 +540,7 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
427
540
  const stopSignals: Array<Effect.Effect<"cancelled" | "timeout">> = [
428
541
  Deferred.await(cancelled),
429
542
  ];
430
- if (options.timeout !== undefined) {
543
+ if (options.timeout !== undefined && timing === "timed") {
431
544
  stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout" as const));
432
545
  }
433
546
  const result = yield* Effect.raceFirst(
@@ -445,7 +558,14 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
445
558
  return { _tag: "Interrupted" as const, reason: result.reason, settled };
446
559
  });
447
560
 
448
- return { halt, stop, runPhase };
561
+ return {
562
+ halt,
563
+ stop,
564
+ runPhase,
565
+ isCancelled: () => cancellationArrived,
566
+ stopped,
567
+ settleTimeout,
568
+ };
449
569
  });
450
570
 
451
571
  /**
@@ -487,18 +607,6 @@ const inScope = <E, R>(
487
607
  }),
488
608
  ).pipe(Effect.asVoid);
489
609
 
490
- const interrupted = <A extends Action.Any, E>(
491
- plan: Plan.Plan<A, Plan.Coverage>,
492
- mode: Report["mode"],
493
- reason: InterruptReason,
494
- outcomes: ReadonlyMap<string, Outcome<E>>,
495
- bodiesStarted: boolean,
496
- ) =>
497
- new ExecutionInterrupted({
498
- reason,
499
- report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
500
- });
501
-
502
610
  /**
503
611
  * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
504
612
  * handler that interrupted itself stops admission.
@@ -525,265 +633,474 @@ const unsuccessful = <T, E>(
525
633
  return undefined;
526
634
  };
527
635
 
636
+ /** The observers of one run, and the identifier their events carry. */
637
+ type Observation<R> = {
638
+ readonly observers: ReadonlyArray<Observer.Observer<R>>;
639
+ readonly runId: string | undefined;
640
+ };
641
+
642
+ /**
643
+ * Creates the run's event emitter, and sends observers a report-less `RunFinished` if
644
+ * the fiber running `body` is interrupted.
645
+ */
646
+ const observed = <A extends Action.Any, T, E, R>(
647
+ plan: Plan.Plan<A, Plan.Coverage>,
648
+ mode: Report["mode"],
649
+ observation: Observation<R>,
650
+ control: Effect.Success<ReturnType<typeof makeControl>>,
651
+ outcomes: ReadonlyMap<string, Outcome>,
652
+ retain: Retain,
653
+ body: (emitter: Emitter<R>) => Effect.Effect<T, E, R>,
654
+ ): Effect.Effect<T, E, R> =>
655
+ Effect.gen(function* () {
656
+ const emitter = yield* makeEmitter({
657
+ plan,
658
+ mode,
659
+ runId: observation.runId,
660
+ observers: observation.observers,
661
+ outcomes,
662
+ stopped: control.stopped,
663
+ grace: control.settleTimeout,
664
+ retain,
665
+ });
666
+
667
+ return yield* Effect.onInterrupt(body(emitter), () => emitter.interrupted);
668
+ });
669
+
528
670
  const execute = <A extends Action.Any, E, R>(
529
671
  plan: Plan.Plan<A, Plan.Coverage>,
530
672
  resolved: Resolved<E, R>,
673
+ interaction: Interaction.Interaction<E, R> | undefined,
674
+ observation: Observation<R>,
531
675
  options: ControlOptions,
532
676
  subscribe: Subscribe | undefined,
533
677
  retain: Retain,
534
678
  ): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
535
679
  Effect.gen(function* () {
536
680
  const outcomes = new Map<string, Outcome<E>>();
537
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
681
+ const control = yield* makeControl(options, subscribe);
682
+ const { halt, stop, runPhase, isCancelled } = control;
538
683
  let bodiesStarted = false;
539
684
 
540
- const runOccurrence = (occurrence: Occurrence) => {
541
- if (halt.reason !== undefined) return Effect.void;
542
-
543
- const handler = resolved.get(occurrence.id);
544
- if (handler === undefined) return Effect.void;
545
-
546
- let phase: Handler.Phase = "prepare";
547
- const end = (outcome: Outcome<E>) => {
548
- outcomes.set(occurrence.id, outcome);
549
-
550
- return exitOf(outcome);
551
- };
552
- const fail = (cause: Cause.Cause<E>) => {
553
- stop("failure");
554
-
555
- return end({ _tag: "Failed", phase, ...failureOf(cause) });
556
- };
557
-
558
- const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
559
- Effect.gen(function* () {
560
- let step: Handler.Step<E, R>;
561
- if (handler.prepares) {
562
- const preparation = yield* runPhase(handler.prepare(scope), unsettled);
563
- const stopped = unsuccessful("prepare", preparation, stop);
564
- if (stopped !== undefined) return end(stopped);
565
- if (preparation._tag !== "Done") return Exit.void;
566
- if (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);
567
- step = preparation.exit.value;
568
- // The occurrence has started, so a sibling failure or timeout lets it
569
- // finish. Cancellation that arrived while preparing keeps it from
570
- // applying, and the prepared value is discarded.
571
- if (step._tag === "Apply" && halt.reason === "cancelled") return Exit.void;
572
- } else {
573
- const started = yield* Effect.exit(handler.prepare(scope));
574
- if (Exit.isFailure(started)) return fail(started.cause);
575
- step = started.value;
576
- }
577
- if (step._tag === "Skip") return end({ _tag: "Skipped", reason: step.reason });
578
-
579
- phase = "apply";
580
- bodiesStarted = true;
581
- const applied = yield* runPhase(step.apply, unsettled);
582
- const stopped = unsuccessful("apply", applied, stop);
583
- if (stopped !== undefined) return end(stopped);
584
- if (applied._tag !== "Done") return Exit.void;
585
- if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
586
-
587
- return end({ _tag: "Completed" });
588
- });
589
-
590
- // A finalizer that fails before the report is part of the execution: it fails an
591
- // occurrence that otherwise ended normally. An interrupted occurrence keeps its
592
- // outcome, and the failure is logged.
593
- const onCleanupFailure = (cause: Cause.Cause<never>) =>
594
- Effect.suspend(() => {
595
- const outcome = outcomes.get(occurrence.id);
596
- if (outcome?._tag === "Interrupted") {
597
- return logCleanupFailure({ occurrence: occurrence.id })(cause);
598
- }
599
- stop("failure");
600
- outcomes.set(occurrence.id, {
601
- _tag: "Failed",
602
- phase,
603
- ...failureOf(
604
- outcome?._tag === "Failed"
605
- ? Cause.combine(outcome.cause, cause)
606
- : cause,
607
- ),
608
- });
685
+ return yield* observed(plan, "execute", observation, control, outcomes, retain, (emitter) =>
686
+ Effect.gen(function* () {
687
+ const runOccurrence = (occurrence: Occurrence) => {
688
+ if (halt.reason !== undefined) return Effect.void;
609
689
 
610
- return Effect.void;
611
- });
690
+ const handler = resolved.get(occurrence.id);
691
+ if (handler === undefined) return Effect.void;
612
692
 
613
- return inScope(retain, occurrence.id, use, onCleanupFailure);
614
- };
693
+ let phase: Handler.Phase = "prepare";
694
+ const end = (outcome: Outcome<E>) => {
695
+ outcomes.set(occurrence.id, outcome);
615
696
 
616
- const runNode = (node: Node): Effect.Effect<void, never, R> => {
617
- switch (node._tag) {
618
- case "Occurrence":
619
- return runOccurrence(node);
620
- case "Sequence":
621
- return Effect.forEach(node.children, runNode, { discard: true });
622
- }
697
+ return exitOf(outcome);
698
+ };
699
+ const fail = (cause: Cause.Cause<E>) => {
700
+ stop("failure");
623
701
 
624
- // Sibling failures stop admission through `halt`; they never interrupt branches.
625
- return forEachBranch(node.branches, node.concurrency, runNode);
626
- };
702
+ return end({ _tag: "Failed", phase, ...failureOf(cause) });
703
+ };
627
704
 
628
- for (const step of plan.steps) {
629
- // Migration steps are barriers: a step starts only after the previous one settled.
630
- if (halt.reason !== undefined) break;
631
- yield* runNode(step.node);
632
- }
705
+ // Observers are awaited before each phase, so admission is checked again after
706
+ // they hear that it is starting. A handler that prepares has started once
707
+ // preparation succeeds, and from then on only cancellation keeps it from going on.
708
+ const admitted = () =>
709
+ handler.prepares ? !isCancelled() : halt.reason === undefined;
633
710
 
634
- if (halt.reason === undefined)
635
- return report(plan, "execute", "completed", outcomes, bodiesStarted);
636
- if (halt.reason === "failure") {
637
- const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
711
+ const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
712
+ Effect.gen(function* () {
713
+ let step: Handler.Step<E, R>;
714
+ if (handler.prepares) {
715
+ yield* emitter.phaseStarted(occurrence, "prepare");
716
+ if (halt.reason !== undefined) return Exit.void;
717
+ const preparation = yield* runPhase(
718
+ handler.prepare(scope),
719
+ unsettled,
720
+ );
721
+ const stopped = unsuccessful("prepare", preparation, stop);
722
+ if (stopped !== undefined) return end(stopped);
723
+ if (preparation._tag !== "Done") return Exit.void;
724
+ if (Exit.isFailure(preparation.exit)) {
725
+ return fail(preparation.exit.cause);
726
+ }
727
+ step = preparation.exit.value;
728
+ // The occurrence has started, so a sibling failure or timeout lets it
729
+ // finish. Cancellation that arrived while preparing keeps it from
730
+ // applying, and the prepared value is discarded.
731
+ if (step._tag === "Apply" && halt.reason === "cancelled") {
732
+ return Exit.void;
733
+ }
734
+ } else {
735
+ const started = yield* Effect.exit(handler.prepare(scope));
736
+ if (Exit.isFailure(started)) return fail(started.cause);
737
+ step = started.value;
738
+ }
739
+ if (step._tag === "Skip") {
740
+ return end({ _tag: "Skipped", reason: step.reason });
741
+ }
742
+ if (step._tag === "Confirm") {
743
+ // The interaction preflight guarantees one for every manual occurrence.
744
+ if (interaction === undefined) return Exit.void;
745
+
746
+ phase = "confirmation";
747
+ yield* emitter.phaseStarted(occurrence, "confirmation");
748
+ if (!admitted()) return Exit.void;
749
+ // The person may start changing state as soon as they are asked.
750
+ bodiesStarted = true;
751
+ const asked = yield* runPhase(
752
+ interaction.confirm({ occurrence }),
753
+ unsettled,
754
+ "untimed",
755
+ );
756
+ const unanswered = unsuccessful("confirmation", asked, stop);
757
+ if (unanswered !== undefined) return end(unanswered);
758
+ if (asked._tag !== "Done") return Exit.void;
759
+ if (Exit.isFailure(asked.exit)) return fail(asked.exit.cause);
760
+ if (asked.exit.value === "declined") {
761
+ stop("failure");
762
+
763
+ return end({ _tag: "Declined" });
764
+ }
765
+ if (step.verify === undefined) {
766
+ return end({
767
+ _tag: "Completed",
768
+ performer: "manual",
769
+ confirmation: "asserted",
770
+ });
771
+ }
772
+
773
+ phase = "verification";
774
+ // Cancellation that arrived with the confirmation, or while observers
775
+ // heard that the check is starting, keeps the check from starting.
776
+ const unverified = () =>
777
+ end({
778
+ _tag: "Interrupted",
779
+ phase: "verification",
780
+ reason: "cancelled",
781
+ settled: true,
782
+ });
783
+ if (isCancelled()) return unverified();
784
+ yield* emitter.phaseStarted(occurrence, "verification");
785
+ if (isCancelled()) return unverified();
786
+ const checked = yield* runPhase(step.verify, unsettled);
787
+ const unchecked = unsuccessful("verification", checked, stop);
788
+ if (unchecked !== undefined) return end(unchecked);
789
+ if (checked._tag !== "Done") return Exit.void;
790
+ if (Exit.isFailure(checked.exit)) return fail(checked.exit.cause);
791
+
792
+ return end({
793
+ _tag: "Completed",
794
+ performer: "manual",
795
+ confirmation: "verified",
796
+ });
797
+ }
638
798
 
639
- return yield* new ExecutionFailed({
640
- failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
641
- report: result,
642
- });
643
- }
799
+ phase = "apply";
800
+ yield* emitter.phaseStarted(occurrence, "apply");
801
+ if (!admitted()) return Exit.void;
802
+ bodiesStarted = true;
803
+ const applied = yield* runPhase(step.apply, unsettled);
804
+ const stopped = unsuccessful("apply", applied, stop);
805
+ if (stopped !== undefined) return end(stopped);
806
+ if (applied._tag !== "Done") return Exit.void;
807
+ if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
808
+
809
+ return end({ _tag: "Completed", performer: "automated" });
810
+ });
644
811
 
645
- return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
812
+ // A finalizer that fails before the report is part of the execution: it fails
813
+ // an occurrence that otherwise ended normally. An interrupted occurrence keeps
814
+ // its outcome, and the failure is logged.
815
+ const onCleanupFailure = (cause: Cause.Cause<never>) =>
816
+ Effect.suspend(() => {
817
+ const outcome = outcomes.get(occurrence.id);
818
+ if (outcome?._tag === "Interrupted") {
819
+ return logCleanupFailure({ occurrence: occurrence.id })(cause);
820
+ }
821
+ stop("failure");
822
+ outcomes.set(occurrence.id, {
823
+ _tag: "Failed",
824
+ phase,
825
+ ...failureOf(
826
+ outcome?._tag === "Failed"
827
+ ? Cause.combine(outcome.cause, cause)
828
+ : cause,
829
+ ),
830
+ });
831
+
832
+ return Effect.void;
833
+ });
834
+
835
+ // Observers hear the outcome once the scope has closed, when a cleanup failure
836
+ // can no longer change it.
837
+ return Effect.andThen(
838
+ inScope(retain, occurrence.id, use, onCleanupFailure),
839
+ emitter.settled(occurrence),
840
+ );
841
+ };
842
+
843
+ const runNode = (node: Node): Effect.Effect<void, never, R> => {
844
+ switch (node._tag) {
845
+ case "Occurrence":
846
+ return runOccurrence(node);
847
+ case "Sequence":
848
+ return Effect.forEach(node.children, runNode, { discard: true });
849
+ }
850
+
851
+ // Sibling failures stop admission through `halt`; they never interrupt branches.
852
+ return forEachBranch(node.branches, node.concurrency, runNode);
853
+ };
854
+
855
+ yield* emitter.runStarted;
856
+ for (const step of plan.steps) {
857
+ // Migration steps are barriers: a step starts only after the previous one
858
+ // settled.
859
+ if (halt.reason !== undefined) break;
860
+ if (step.omitted) continue;
861
+ yield* emitter.stepStarted(step);
862
+ yield* runNode(step.node);
863
+ yield* emitter.stepSettled(step);
864
+ }
865
+
866
+ const reason = halt.reason;
867
+ const status =
868
+ reason === undefined
869
+ ? "completed"
870
+ : reason === "failure"
871
+ ? "failed"
872
+ : "interrupted";
873
+ yield* emitter.runFinished(status);
874
+ const result = report(
875
+ plan,
876
+ "execute",
877
+ status,
878
+ outcomes,
879
+ bodiesStarted,
880
+ emitter.failures,
881
+ );
882
+ if (reason === undefined) return result;
883
+ if (reason === "failure") {
884
+ return yield* new ExecutionFailed({
885
+ failures: result.occurrences.filter(
886
+ (entry) => entry.outcome._tag === "Failed",
887
+ ),
888
+ declined: result.occurrences.filter(
889
+ (entry) => entry.outcome._tag === "Declined",
890
+ ),
891
+ report: result,
892
+ });
893
+ }
894
+
895
+ return yield* new ExecutionInterrupted({ reason, report: result });
896
+ }),
897
+ );
646
898
  });
647
899
 
648
900
  const dryRun = <A extends Action.Any, E, R>(
649
901
  plan: Plan.Plan<A, Plan.Coverage>,
650
902
  resolved: Resolved<E, R>,
903
+ observation: Observation<R>,
651
904
  options: ControlOptions,
652
905
  subscribe: Subscribe | undefined,
653
906
  retain: Retain,
654
907
  ): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
655
908
  Effect.gen(function* () {
656
909
  const outcomes = new Map<string, Outcome<E>>();
657
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
910
+ const control = yield* makeControl(options, subscribe);
911
+ const { halt, stop, runPhase } = control;
658
912
  let failedAt: string | undefined;
659
913
 
660
- /** Runs a prepare phase in the occurrence's scope and records what it predicts. */
661
- const prepare = (id: string, handler: Internal<E, R>) => {
662
- const end = (outcome: Outcome<E>) => {
663
- outcomes.set(id, outcome);
664
-
665
- return exitOf(outcome);
666
- };
667
- const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
668
- Effect.gen(function* () {
669
- const preparation = yield* runPhase(handler.prepare(scope), unsettled);
670
- const stopped = unsuccessful("prepare", preparation, stop);
671
- if (stopped !== undefined) return end(stopped);
672
- if (preparation._tag !== "Done") return Exit.void;
673
- if (Exit.isFailure(preparation.exit)) {
674
- failedAt = id;
675
-
676
- return end({
677
- _tag: "PreparationFailed",
678
- ...failureOf(preparation.exit.cause),
679
- });
680
- }
681
- // A dry run never applies: the prepared value is discarded.
682
- const step = preparation.exit.value;
683
-
684
- return end(
685
- step._tag === "Skip"
686
- ? { _tag: "WouldSkip", reason: step.reason }
687
- : { _tag: "WouldExecute", evaluated: true },
688
- );
689
- });
690
- const onCleanupFailure = (cause: Cause.Cause<never>) =>
691
- Effect.suspend(() => {
692
- const outcome = outcomes.get(id);
693
- if (outcome?._tag === "Interrupted") {
694
- return logCleanupFailure({ occurrence: id })(cause);
695
- }
696
- failedAt ??= id;
697
- outcomes.set(id, {
698
- _tag: "PreparationFailed",
699
- ...failureOf(
700
- outcome?._tag === "PreparationFailed"
701
- ? Cause.combine(outcome.cause, cause)
702
- : cause,
703
- ),
704
- });
914
+ return yield* observed(plan, "dry-run", observation, control, outcomes, retain, (emitter) =>
915
+ Effect.gen(function* () {
916
+ const settle = (occurrence: Occurrence, outcome: Outcome<E>) => {
917
+ outcomes.set(occurrence.id, outcome);
705
918
 
706
- return Effect.void;
707
- });
919
+ return emitter.settled(occurrence);
920
+ };
708
921
 
709
- return inScope(retain, id, use, onCleanupFailure);
710
- };
922
+ /** Runs a prepare phase in the occurrence's scope and records what it predicts. */
923
+ const prepare = (occurrence: Occurrence, handler: Internal<E, R>) => {
924
+ const id = occurrence.id;
925
+ const end = (outcome: Outcome<E>) => {
926
+ outcomes.set(id, outcome);
711
927
 
712
- /** Returns whether the node would or might change state. */
713
- const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
714
- Effect.gen(function* () {
715
- if (node._tag === "Sequence") {
716
- let current = dirty;
717
- for (const child of node.children) current = yield* visit(child, current);
928
+ return exitOf(outcome);
929
+ };
930
+ const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
931
+ Effect.gen(function* () {
932
+ yield* emitter.phaseStarted(occurrence, "prepare");
933
+ // Observers are awaited, so the run may have stopped while they heard it.
934
+ if (halt.reason !== undefined) return Exit.void;
935
+ const preparation = yield* runPhase(handler.prepare(scope), unsettled);
936
+ const stopped = unsuccessful("prepare", preparation, stop);
937
+ if (stopped !== undefined) return end(stopped);
938
+ if (preparation._tag !== "Done") return Exit.void;
939
+ if (Exit.isFailure(preparation.exit)) {
940
+ failedAt = id;
941
+
942
+ return end({
943
+ _tag: "PreparationFailed",
944
+ ...failureOf(preparation.exit.cause),
945
+ });
946
+ }
947
+ // A dry run never applies: the prepared value is discarded.
948
+ const step = preparation.exit.value;
949
+
950
+ return end(
951
+ step._tag === "Skip"
952
+ ? { _tag: "WouldSkip", reason: step.reason }
953
+ : {
954
+ _tag: "WouldExecute",
955
+ evaluated: true,
956
+ performer: handler.performer,
957
+ },
958
+ );
959
+ });
960
+ const onCleanupFailure = (cause: Cause.Cause<never>) =>
961
+ Effect.suspend(() => {
962
+ const outcome = outcomes.get(id);
963
+ if (outcome?._tag === "Interrupted") {
964
+ return logCleanupFailure({ occurrence: id })(cause);
965
+ }
966
+ failedAt ??= id;
967
+ outcomes.set(id, {
968
+ _tag: "PreparationFailed",
969
+ ...failureOf(
970
+ outcome?._tag === "PreparationFailed"
971
+ ? Cause.combine(outcome.cause, cause)
972
+ : cause,
973
+ ),
974
+ });
975
+
976
+ return Effect.void;
977
+ });
718
978
 
719
- return current;
720
- }
721
- if (node._tag === "Parallel") {
722
- // Branches are independent: each starts from the state before the group.
723
- // They are evaluated one at a time so the report is deterministic.
724
- let changed = dirty;
725
- for (const branch of node.branches)
726
- changed = (yield* visit(branch, dirty)) || changed;
727
-
728
- return changed;
729
- }
979
+ return Effect.andThen(
980
+ inScope(retain, id, use, onCleanupFailure),
981
+ emitter.settled(occurrence),
982
+ );
983
+ };
730
984
 
731
- const handler = resolved.get(node.id);
732
- if (handler === undefined || halt.reason !== undefined) return dirty;
733
- if (failedAt !== undefined) {
734
- outcomes.set(node.id, {
735
- _tag: "Undetermined",
736
- reason: `Execution would stop at the failed preparation of "${failedAt}".`,
985
+ /** Returns whether the node would or might change state. */
986
+ const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
987
+ Effect.gen(function* () {
988
+ if (node._tag === "Sequence") {
989
+ let current = dirty;
990
+ for (const child of node.children)
991
+ current = yield* visit(child, current);
992
+
993
+ return current;
994
+ }
995
+ if (node._tag === "Parallel") {
996
+ // Branches are independent: each starts from the state before the group.
997
+ // They are evaluated one at a time so the report is deterministic.
998
+ let changed = dirty;
999
+ for (const branch of node.branches)
1000
+ changed = (yield* visit(branch, dirty)) || changed;
1001
+
1002
+ return changed;
1003
+ }
1004
+
1005
+ const handler = resolved.get(node.id);
1006
+ if (handler === undefined || halt.reason !== undefined) return dirty;
1007
+ if (failedAt !== undefined) {
1008
+ yield* settle(node, {
1009
+ _tag: "Undetermined",
1010
+ reason: `Execution would stop at the failed preparation of "${failedAt}".`,
1011
+ performer: handler.performer,
1012
+ });
1013
+
1014
+ return true;
1015
+ }
1016
+ if (!handler.prepares) {
1017
+ yield* settle(node, {
1018
+ _tag: "WouldExecute",
1019
+ evaluated: false,
1020
+ performer: handler.performer,
1021
+ });
1022
+
1023
+ return true;
1024
+ }
1025
+ if (dirty) {
1026
+ yield* settle(node, {
1027
+ _tag: "Undetermined",
1028
+ reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
1029
+ performer: handler.performer,
1030
+ });
1031
+
1032
+ return true;
1033
+ }
1034
+
1035
+ yield* prepare(node, handler);
1036
+
1037
+ return outcomes.get(node.id)?._tag !== "WouldSkip";
737
1038
  });
738
1039
 
739
- return true;
1040
+ yield* emitter.runStarted;
1041
+ // Later migrations conservatively depend on every earlier migration.
1042
+ let dirty = false;
1043
+ for (const step of plan.steps) {
1044
+ if (halt.reason !== undefined) break;
1045
+ if (step.omitted) continue;
1046
+ yield* emitter.stepStarted(step);
1047
+ dirty = yield* visit(step.node, dirty);
1048
+ yield* emitter.stepSettled(step);
740
1049
  }
741
- if (!handler.prepares) {
742
- outcomes.set(node.id, { _tag: "WouldExecute", evaluated: false });
743
1050
 
744
- return true;
745
- }
746
- if (dirty) {
747
- outcomes.set(node.id, {
748
- _tag: "Undetermined",
749
- reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
1051
+ const reason = halt.reason;
1052
+ if (reason !== undefined && reason !== "failure") {
1053
+ yield* emitter.runFinished("interrupted");
1054
+
1055
+ return yield* new ExecutionInterrupted({
1056
+ reason,
1057
+ report: report(
1058
+ plan,
1059
+ "dry-run",
1060
+ "interrupted",
1061
+ outcomes,
1062
+ false,
1063
+ emitter.failures,
1064
+ ),
750
1065
  });
751
-
752
- return true;
753
1066
  }
754
1067
 
755
- yield* prepare(node.id, handler);
1068
+ const status = failedAt === undefined ? "would-complete" : "would-fail";
1069
+ yield* emitter.runFinished(status);
756
1070
 
757
- return outcomes.get(node.id)?._tag !== "WouldSkip";
758
- });
759
-
760
- // Later migrations conservatively depend on every earlier migration.
761
- let dirty = false;
762
- for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
763
-
764
- if (halt.reason !== undefined && halt.reason !== "failure") {
765
- return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
766
- }
767
-
768
- return report(
769
- plan,
770
- "dry-run",
771
- failedAt === undefined ? "would-complete" : "would-fail",
772
- outcomes,
773
- false,
1071
+ return report(plan, "dry-run", status, outcomes, false, emitter.failures);
1072
+ }),
774
1073
  );
775
1074
  });
776
1075
 
777
- const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.Any>(
1076
+ const run = <
1077
+ A extends Action.Any,
1078
+ C extends Plan.Coverage,
1079
+ H extends Handler.Any,
1080
+ I extends Interaction.Any,
1081
+ O extends Observer.Any,
1082
+ >(
778
1083
  plan: Plan.Plan<A, C>,
779
- options: Options<H>,
1084
+ options: Options<H, I, O>,
780
1085
  subscribe: Subscribe | undefined,
781
1086
  retain: Retain,
782
- ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> => {
783
- // Handlers are covariant in their errors and services, and `Errors<H>` and
784
- // `Requirements<H>` collect them from each handler in `H`, so every handler fits this
785
- // shape. From here on the compiler checks both channels.
786
- const handlers: ReadonlyArray<Internal<Errors<H>, Requirements<H>>> = options.handlers ?? [];
1087
+ ): Effect.Effect<
1088
+ Report<A, Errors<H, I>>,
1089
+ ExecutionError<A, Errors<H, I>>,
1090
+ Requirements<H, I, O>
1091
+ > => {
1092
+ // Handlers, interactions, and observers are covariant in their errors and services,
1093
+ // and `Errors<H, I>` and `Requirements<H, I, O>` collect them from each handler in `H`,
1094
+ // from `I`, and from each observer in `O`, so all of them fit these shapes. From here
1095
+ // on the compiler checks both channels.
1096
+ const handlers: ReadonlyArray<Internal<Errors<H, I>, Requirements<H, I, O>>> =
1097
+ options.handlers ?? [];
1098
+ const interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I, O>> | undefined =
1099
+ options.interaction;
1100
+ const observation: Observation<Requirements<H, I, O>> = {
1101
+ observers: options.observers ?? [],
1102
+ runId: options.runId,
1103
+ };
787
1104
 
788
1105
  return Effect.gen(function* () {
789
1106
  const checked = coverage(plan, handlers);
@@ -800,14 +1117,42 @@ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.An
800
1117
  });
801
1118
  }
802
1119
 
803
- return options.dryRun === true
804
- ? yield* dryRun(plan, checked.resolved, options, subscribe, retain)
805
- : yield* execute(plan, checked.resolved, options, subscribe, retain);
1120
+ if (options.dryRun === true) {
1121
+ return yield* dryRun(plan, checked.resolved, observation, options, subscribe, retain);
1122
+ }
1123
+
1124
+ // Nobody can answer for manual work, so the run must not start and stop halfway.
1125
+ const manual = plan.occurrences.filter(
1126
+ (occurrence) => checked.resolved.get(occurrence.id)?.performer === "manual",
1127
+ );
1128
+ if (manual.length > 0 && interaction === undefined) {
1129
+ return yield* new InteractionUnavailable({
1130
+ occurrences: manual,
1131
+ report: report(
1132
+ plan,
1133
+ "execute",
1134
+ "not-started",
1135
+ new Map<string, Outcome<never>>(),
1136
+ false,
1137
+ ),
1138
+ });
1139
+ }
1140
+
1141
+ return yield* execute(
1142
+ plan,
1143
+ checked.resolved,
1144
+ interaction,
1145
+ observation,
1146
+ options,
1147
+ subscribe,
1148
+ retain,
1149
+ );
806
1150
  });
807
1151
  };
808
1152
 
809
1153
  /**
810
- * Runs a plan as an Effect. Coverage is checked before any handler phase runs. Steps
1154
+ * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,
1155
+ * are checked before any handler phase runs. Steps
811
1156
  * are sequential barriers; parallel groups run their branches concurrently. On failure,
812
1157
  * no new action starts, and actions already running settle before the effect fails
813
1158
  * with the partial report.
@@ -819,42 +1164,51 @@ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.An
819
1164
  *
820
1165
  * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
821
1166
  * signal passed to Promise callbacks. The effect then ends as interrupted, without a
822
- * report.
1167
+ * report. Observers receive a final `RunFinished` event without a report, delivered
1168
+ * within `settleTimeout`.
823
1169
  *
824
- * @since @next
1170
+ * @since 0.0.1
825
1171
  */
826
1172
  export const effect = <
827
1173
  A extends Action.Any,
828
1174
  C extends Plan.Coverage,
829
1175
  H extends Handler.Any = never,
1176
+ I extends Interaction.Any = never,
1177
+ O extends Observer.Any = never,
830
1178
  >(
831
1179
  plan: Plan.Plan<A, C>,
832
- options: Options<H> & CoverageCheck<A, H, C>,
833
- ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> =>
1180
+ options: Options<H, I, O> & CoverageCheck<A, H, C>,
1181
+ ): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I, O>> =>
834
1182
  run(plan, options, undefined, () => {});
835
1183
 
836
1184
  type ServicesOption<R, LE> = [R] extends [never]
837
1185
  ? {
838
- /** Handlers without Effect services need none. */
1186
+ /** Handlers, interactions, and observers without Effect services need none. */
839
1187
  readonly services?: Context.Context<never> | Layer.Layer<never, LE>;
840
1188
  }
841
1189
  : {
842
- /** Supplies the handlers' Effect services. */
1190
+ /** Supplies the Effect services of the handlers, the interaction, and the observers. */
843
1191
  readonly services: Context.Context<R> | Layer.Layer<R, LE>;
844
1192
  };
845
1193
 
846
- /** @since @next */
847
- export type PromiseOptions<H extends Handler.Any> = Options<H> & {
1194
+ /** @since 0.0.1 */
1195
+ export type PromiseOptions<
1196
+ H extends Handler.Any,
1197
+ I extends Interaction.Any = never,
1198
+ O extends Observer.Any = never,
1199
+ > = Options<H, I, O> & {
848
1200
  /**
849
- * Explicit cancellation. Aborting stops admission, interrupts running actions, and
850
- * rejects with `ExecutionInterrupted` and the partial report.
1201
+ * Explicit cancellation. Aborting stops admission, interrupts running actions and
1202
+ * pending confirmations, and rejects with `ExecutionInterrupted` and the partial
1203
+ * report.
851
1204
  */
852
1205
  readonly signal?: AbortSignal;
853
1206
  };
854
1207
 
855
1208
  /**
856
1209
  * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
857
- * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
1210
+ * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying
1211
+ * the partial report.
858
1212
  * Building a supplied services layer can also reject with the layer's own error,
859
1213
  * without a report.
860
1214
  *
@@ -865,17 +1219,22 @@ export type PromiseOptions<H extends Handler.Any> = Options<H> & {
865
1219
  * until it settles, possibly forever, and close in that order. A cleanup failure after
866
1220
  * the Promise resolved is logged through Effect.
867
1221
  *
868
- * @since @next
1222
+ * @since 0.0.1
869
1223
  */
870
1224
  export const runPromise = <
871
1225
  A extends Action.Any,
872
1226
  C extends Plan.Coverage,
873
1227
  H extends Handler.Any = never,
1228
+ I extends Interaction.Any = never,
1229
+ // After `LE`, so explicit type arguments written for earlier releases keep their meaning.
874
1230
  LE = never,
1231
+ O extends Observer.Any = never,
875
1232
  >(
876
1233
  plan: Plan.Plan<A, C>,
877
- options: PromiseOptions<H> & ServicesOption<Requirements<H>, LE> & CoverageCheck<A, H, C>,
878
- ): Promise<Report<A, Errors<H>>> => {
1234
+ options: PromiseOptions<H, I, O> &
1235
+ ServicesOption<Requirements<H, I, O>, LE> &
1236
+ CoverageCheck<A, H, C>,
1237
+ ): Promise<Report<A, Errors<H, I>>> => {
879
1238
  const { signal } = options;
880
1239
  const notStarted = () =>
881
1240
  new ExecutionInterrupted({
@@ -884,7 +1243,7 @@ export const runPromise = <
884
1243
  plan,
885
1244
  options.dryRun === true ? "dry-run" : "execute",
886
1245
  "interrupted",
887
- new Map<string, Outcome<Errors<H>>>(),
1246
+ new Map<string, Outcome<Errors<H, I>>>(),
888
1247
  false,
889
1248
  ),
890
1249
  });
@@ -957,7 +1316,7 @@ export const runPromise = <
957
1316
  // `ServicesOption` requires services that cover every requirement. A layer that
958
1317
  // fails to build rejects with its own error.
959
1318
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion
960
- cancellable as Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>> | LE>,
1319
+ cancellable as Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>> | LE>,
961
1320
  )
962
1321
  .finally(() => signal?.removeEventListener("abort", onAbort))
963
1322
  .then((exit) => {