deltafold 0.2.0 → 0.2.2

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 (48) hide show
  1. package/README.md +33 -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-f2Zy7NQO.d.ts} +41 -41
  8. package/dist/{document-DWHsgywm.d.ts.map → document-f2Zy7NQO.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 +437 -105
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +750 -273
  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-BsMlK5xD.d.ts} +126 -116
  22. package/dist/{package-BfBYnaCz.d.ts.map → package-BsMlK5xD.d.ts.map} +1 -1
  23. package/package.json +5 -5
  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 +485 -313
  28. package/src/features/execution/handler.ts +30 -30
  29. package/src/features/execution/interaction.ts +11 -11
  30. package/src/features/execution/observation.ts +489 -0
  31. package/src/features/execution/observer.ts +395 -0
  32. package/src/features/package.ts +13 -8
  33. package/src/features/planning/history.ts +10 -10
  34. package/src/features/planning/identifiers.ts +7 -4
  35. package/src/features/planning/resolve-error.ts +13 -13
  36. package/src/features/planning/resolve.ts +11 -4
  37. package/src/features/planning/validate.ts +1 -1
  38. package/src/foundation/action.ts +17 -17
  39. package/src/foundation/change.ts +10 -10
  40. package/src/foundation/instruction.ts +5 -5
  41. package/src/foundation/migration.ts +12 -12
  42. package/src/foundation/plan.ts +23 -18
  43. package/src/foundation/rule.ts +6 -6
  44. package/src/foundation/shortcut.ts +6 -6
  45. package/src/foundation/version.ts +6 -6
  46. package/src/index.ts +14 -12
  47. package/src/renderers/html.ts +1 -1
  48. package/src/renderers/markdown.ts +1 -1
@@ -18,12 +18,14 @@ 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
20
  import type * as Interaction from "./interaction.ts";
21
+ import { makeEmitter, type Emitter } from "./observation.ts";
22
+ import type * as Observer from "./observer.ts";
21
23
  import { SettlementReference } from "./settlement.ts";
22
24
 
23
25
  /**
24
26
  * What happened to one occurrence, or what a dry run predicts.
25
27
  *
26
- * @since @next
28
+ * @since 0.0.1
27
29
  */
28
30
  export type Outcome<E = unknown> =
29
31
  | { readonly _tag: "Completed"; readonly performer: "automated" }
@@ -83,13 +85,13 @@ export type Outcome<E = unknown> =
83
85
  readonly cause: Cause.Cause<E>;
84
86
  };
85
87
 
86
- /** @since @next */
88
+ /** @since 0.0.1 */
87
89
  export type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {
88
90
  readonly occurrence: Occurrence<A>;
89
91
  readonly outcome: Outcome<E>;
90
92
  };
91
93
 
92
- /** @since @next */
94
+ /** @since 0.0.1 */
93
95
  export type Report<A extends Action.Any = Action.Any, E = unknown> = {
94
96
  readonly _tag: "Report";
95
97
  readonly mode: "execute" | "dry-run";
@@ -112,12 +114,14 @@ export type Report<A extends Action.Any = Action.Any, E = unknown> = {
112
114
  readonly bodiesStarted: boolean;
113
115
  /** Progress is not persisted. Rerunning the plan repeats completed actions. */
114
116
  readonly persistence: "none";
117
+ /** Observers that failed or were abandoned. Never affects outcomes or status. */
118
+ readonly observation: ReadonlyArray<Observer.ObservationFailure>;
115
119
  };
116
120
 
117
121
  /**
118
122
  * A handler is missing, duplicated, or bound to a different definition.
119
123
  *
120
- * @since @next
124
+ * @since 0.0.1
121
125
  */
122
126
  export type CoverageIssue = {
123
127
  readonly _tag: "Missing" | "Duplicate" | "Mismatched";
@@ -142,7 +146,7 @@ const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
142
146
  * For an occurrence that a rule produced, the issue names the rule and the occurrences
143
147
  * it replaced.
144
148
  *
145
- * @since @next
149
+ * @since 0.0.1
146
150
  */
147
151
  export class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{
148
152
  readonly issues: ReadonlyArray<CoverageIssue>;
@@ -164,7 +168,7 @@ const InteractionUnavailableBase = Data.TaggedError("InteractionUnavailable");
164
168
  * The plan has manual handlers, and the run has no `interaction` to ask a person. The
165
169
  * run fails before any handler phase or prompt.
166
170
  *
167
- * @since @next
171
+ * @since 0.2.0
168
172
  */
169
173
  export class InteractionUnavailable<
170
174
  A extends Action.Any = Action.Any,
@@ -197,7 +201,7 @@ const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
197
201
  * An occurrence failed, or a person declined manual work. Execution stopped admitting
198
202
  * new actions; started ones settled.
199
203
  *
200
- * @since @next
204
+ * @since 0.0.1
201
205
  */
202
206
  export class ExecutionFailed<
203
207
  A extends Action.Any = Action.Any,
@@ -230,7 +234,7 @@ const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
230
234
  * Why an execution or an occurrence was interrupted: explicit cancellation, a configured
231
235
  * timeout, or an Effect handler that interrupted itself.
232
236
  *
233
- * @since @next
237
+ * @since 0.0.1
234
238
  */
235
239
  export type InterruptReason = "cancelled" | "timeout" | "handler";
236
240
 
@@ -244,7 +248,7 @@ const interruptedBy: Record<InterruptReason, string> = {
244
248
  * Explicit cancellation, a configured timeout, or a handler's own interruption stopped
245
249
  * execution.
246
250
  *
247
- * @since @next
251
+ * @since 0.0.1
248
252
  */
249
253
  export class ExecutionInterrupted<
250
254
  A extends Action.Any = Action.Any,
@@ -266,7 +270,7 @@ export class ExecutionInterrupted<
266
270
  }
267
271
  }
268
272
 
269
- /** @since @next */
273
+ /** @since 0.0.1 */
270
274
  export type ExecutionError<A extends Action.Any, E> =
271
275
  | HandlerCoverageError<A>
272
276
  | InteractionUnavailable<A>
@@ -277,7 +281,7 @@ export type ExecutionError<A extends Action.Any, E> =
277
281
  * Action identifiers of a statically covered plan that no handler in the array
278
282
  * implements.
279
283
  *
280
- * @since @next
284
+ * @since 0.0.1
281
285
  */
282
286
  export type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = "runtime" extends C
283
287
  ? never
@@ -299,20 +303,27 @@ type CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [
299
303
  /**
300
304
  * Errors an execution can report for its occurrences.
301
305
  *
302
- * @since @next
306
+ * @since 0.0.1
303
307
  */
304
308
  export type Errors<H, I = never> = Handler.Error<H> | Interaction.Error<I>;
305
309
 
306
310
  /**
307
- * Effect services an execution requires: the services of its handlers and of its
308
- * interaction.
311
+ * Effect services an execution requires: the services of its handlers, its
312
+ * interaction, and its observers.
309
313
  *
310
- * @since @next
314
+ * @since 0.0.1
311
315
  */
312
- export type Requirements<H, I = never> = Handler.Services<H> | Interaction.Services<I>;
316
+ export type Requirements<H, I = never, O = never> =
317
+ | Handler.Services<H>
318
+ | Interaction.Services<I>
319
+ | Observer.Services<O>;
313
320
 
314
- /** @since @next */
315
- export type Options<H extends Handler.Any, I extends Interaction.Any = never> = {
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
+ > = {
316
327
  readonly handlers?: ReadonlyArray<H>;
317
328
  /**
318
329
  * Asks a person to confirm the work of manual handlers. A run whose plan has manual
@@ -320,6 +331,14 @@ export type Options<H extends Handler.Any, I extends Interaction.Any = never> =
320
331
  * A dry run never asks and does not need it.
321
332
  */
322
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;
323
342
  /**
324
343
  * Run prepare phases without running any apply phase. A prepare phase that may
325
344
  * depend on an earlier action is reported `Undetermined`, because the dry run does
@@ -403,6 +422,7 @@ const report = <A extends Action.Any, E>(
403
422
  status: Report["status"],
404
423
  outcomes: ReadonlyMap<string, Outcome<E>>,
405
424
  bodiesStarted: boolean,
425
+ observation: ReadonlyArray<Observer.ObservationFailure> = [],
406
426
  ): Report<A, E> => ({
407
427
  _tag: "Report",
408
428
  mode,
@@ -416,6 +436,7 @@ const report = <A extends Action.Any, E>(
416
436
  })),
417
437
  bodiesStarted,
418
438
  persistence: "none",
439
+ observation: [...observation],
419
440
  });
420
441
 
421
442
  const failureOf = <E>(cause: Cause.Cause<E>) => ({
@@ -478,10 +499,15 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
478
499
  Effect.gen(function* () {
479
500
  const halt: { reason: StopReason | undefined } = { reason: undefined };
480
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>();
481
504
  const settleTimeout = options.settleTimeout ?? Duration.seconds(5);
482
505
 
483
506
  const stop = (reason: StopReason) => {
484
507
  halt.reason ??= reason;
508
+ if (reason === "cancelled" || reason === "timeout") {
509
+ Deferred.doneUnsafe(stopped, Exit.void);
510
+ }
485
511
  };
486
512
  // A failure can be the first stop reason, so cancellation is also tracked on its own.
487
513
  let cancellationArrived = false;
@@ -532,7 +558,14 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
532
558
  return { _tag: "Interrupted" as const, reason: result.reason, settled };
533
559
  });
534
560
 
535
- return { halt, stop, runPhase, isCancelled: () => cancellationArrived };
561
+ return {
562
+ halt,
563
+ stop,
564
+ runPhase,
565
+ isCancelled: () => cancellationArrived,
566
+ stopped,
567
+ settleTimeout,
568
+ };
536
569
  });
537
570
 
538
571
  /**
@@ -574,18 +607,6 @@ const inScope = <E, R>(
574
607
  }),
575
608
  ).pipe(Effect.asVoid);
576
609
 
577
- const interrupted = <A extends Action.Any, E>(
578
- plan: Plan.Plan<A, Plan.Coverage>,
579
- mode: Report["mode"],
580
- reason: InterruptReason,
581
- outcomes: ReadonlyMap<string, Outcome<E>>,
582
- bodiesStarted: boolean,
583
- ) =>
584
- new ExecutionInterrupted({
585
- reason,
586
- report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
587
- });
588
-
589
610
  /**
590
611
  * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
591
612
  * handler that interrupted itself stops admission.
@@ -612,316 +633,443 @@ const unsuccessful = <T, E>(
612
633
  return undefined;
613
634
  };
614
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
+
615
670
  const execute = <A extends Action.Any, E, R>(
616
671
  plan: Plan.Plan<A, Plan.Coverage>,
617
672
  resolved: Resolved<E, R>,
618
673
  interaction: Interaction.Interaction<E, R> | undefined,
674
+ observation: Observation<R>,
619
675
  options: ControlOptions,
620
676
  subscribe: Subscribe | undefined,
621
677
  retain: Retain,
622
678
  ): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
623
679
  Effect.gen(function* () {
624
680
  const outcomes = new Map<string, Outcome<E>>();
625
- const { halt, stop, runPhase, isCancelled } = yield* makeControl(options, subscribe);
681
+ const control = yield* makeControl(options, subscribe);
682
+ const { halt, stop, runPhase, isCancelled } = control;
626
683
  let bodiesStarted = false;
627
684
 
628
- const runOccurrence = (occurrence: Occurrence) => {
629
- if (halt.reason !== undefined) return Effect.void;
630
-
631
- const handler = resolved.get(occurrence.id);
632
- if (handler === undefined) return Effect.void;
633
-
634
- let phase: Handler.Phase = "prepare";
635
- const end = (outcome: Outcome<E>) => {
636
- outcomes.set(occurrence.id, outcome);
637
-
638
- return exitOf(outcome);
639
- };
640
- const fail = (cause: Cause.Cause<E>) => {
641
- stop("failure");
642
-
643
- return end({ _tag: "Failed", phase, ...failureOf(cause) });
644
- };
645
-
646
- const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
647
- Effect.gen(function* () {
648
- let step: Handler.Step<E, R>;
649
- if (handler.prepares) {
650
- const preparation = yield* runPhase(handler.prepare(scope), unsettled);
651
- const stopped = unsuccessful("prepare", preparation, stop);
652
- if (stopped !== undefined) return end(stopped);
653
- if (preparation._tag !== "Done") return Exit.void;
654
- if (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);
655
- step = preparation.exit.value;
656
- // The occurrence has started, so a sibling failure or timeout lets it
657
- // finish. Cancellation that arrived while preparing keeps it from
658
- // applying, and the prepared value is discarded.
659
- if (step._tag === "Apply" && halt.reason === "cancelled") return Exit.void;
660
- } else {
661
- const started = yield* Effect.exit(handler.prepare(scope));
662
- if (Exit.isFailure(started)) return fail(started.cause);
663
- step = started.value;
664
- }
665
- if (step._tag === "Skip") return end({ _tag: "Skipped", reason: step.reason });
666
- if (step._tag === "Confirm") {
667
- // The interaction preflight guarantees one for every manual occurrence.
668
- if (interaction === undefined) return Exit.void;
669
-
670
- phase = "confirmation";
671
- // The person may start changing state as soon as they are asked.
672
- bodiesStarted = true;
673
- const asked = yield* runPhase(
674
- interaction.confirm({ occurrence }),
675
- unsettled,
676
- "untimed",
677
- );
678
- const unanswered = unsuccessful("confirmation", asked, stop);
679
- if (unanswered !== undefined) return end(unanswered);
680
- if (asked._tag !== "Done") return Exit.void;
681
- if (Exit.isFailure(asked.exit)) return fail(asked.exit.cause);
682
- if (asked.exit.value === "declined") {
683
- stop("failure");
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;
684
689
 
685
- return end({ _tag: "Declined" });
686
- }
687
- if (step.verify === undefined) {
688
- return end({
689
- _tag: "Completed",
690
- performer: "manual",
691
- confirmation: "asserted",
692
- });
693
- }
690
+ const handler = resolved.get(occurrence.id);
691
+ if (handler === undefined) return Effect.void;
694
692
 
695
- phase = "verification";
696
- // Cancellation that arrived with the confirmation keeps the check from
697
- // starting.
698
- if (isCancelled()) {
699
- return end({
700
- _tag: "Interrupted",
701
- phase,
702
- reason: "cancelled",
703
- settled: true,
704
- });
705
- }
706
- const checked = yield* runPhase(step.verify, unsettled);
707
- const unchecked = unsuccessful("verification", checked, stop);
708
- if (unchecked !== undefined) return end(unchecked);
709
- if (checked._tag !== "Done") return Exit.void;
710
- if (Exit.isFailure(checked.exit)) return fail(checked.exit.cause);
711
-
712
- return end({
713
- _tag: "Completed",
714
- performer: "manual",
715
- confirmation: "verified",
716
- });
717
- }
693
+ let phase: Handler.Phase = "prepare";
694
+ const end = (outcome: Outcome<E>) => {
695
+ outcomes.set(occurrence.id, outcome);
718
696
 
719
- phase = "apply";
720
- bodiesStarted = true;
721
- const applied = yield* runPhase(step.apply, unsettled);
722
- const stopped = unsuccessful("apply", applied, stop);
723
- if (stopped !== undefined) return end(stopped);
724
- if (applied._tag !== "Done") return Exit.void;
725
- if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
726
-
727
- return end({ _tag: "Completed", performer: "automated" });
728
- });
729
-
730
- // A finalizer that fails before the report is part of the execution: it fails an
731
- // occurrence that otherwise ended normally. An interrupted occurrence keeps its
732
- // outcome, and the failure is logged.
733
- const onCleanupFailure = (cause: Cause.Cause<never>) =>
734
- Effect.suspend(() => {
735
- const outcome = outcomes.get(occurrence.id);
736
- if (outcome?._tag === "Interrupted") {
737
- return logCleanupFailure({ occurrence: occurrence.id })(cause);
738
- }
739
- stop("failure");
740
- outcomes.set(occurrence.id, {
741
- _tag: "Failed",
742
- phase,
743
- ...failureOf(
744
- outcome?._tag === "Failed"
745
- ? Cause.combine(outcome.cause, cause)
746
- : cause,
747
- ),
748
- });
697
+ return exitOf(outcome);
698
+ };
699
+ const fail = (cause: Cause.Cause<E>) => {
700
+ stop("failure");
749
701
 
750
- return Effect.void;
751
- });
702
+ return end({ _tag: "Failed", phase, ...failureOf(cause) });
703
+ };
752
704
 
753
- return inScope(retain, occurrence.id, use, onCleanupFailure);
754
- };
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;
755
710
 
756
- const runNode = (node: Node): Effect.Effect<void, never, R> => {
757
- switch (node._tag) {
758
- case "Occurrence":
759
- return runOccurrence(node);
760
- case "Sequence":
761
- return Effect.forEach(node.children, runNode, { discard: true });
762
- }
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
+ }
763
798
 
764
- // Sibling failures stop admission through `halt`; they never interrupt branches.
765
- return forEachBranch(node.branches, node.concurrency, runNode);
766
- };
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
+ });
767
811
 
768
- for (const step of plan.steps) {
769
- // Migration steps are barriers: a step starts only after the previous one settled.
770
- if (halt.reason !== undefined) break;
771
- yield* runNode(step.node);
772
- }
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
+ });
773
831
 
774
- if (halt.reason === undefined)
775
- return report(plan, "execute", "completed", outcomes, bodiesStarted);
776
- if (halt.reason === "failure") {
777
- const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
832
+ return Effect.void;
833
+ });
778
834
 
779
- return yield* new ExecutionFailed({
780
- failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
781
- declined: result.occurrences.filter((entry) => entry.outcome._tag === "Declined"),
782
- report: result,
783
- });
784
- }
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
+ }
785
850
 
786
- return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
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
+ );
787
898
  });
788
899
 
789
900
  const dryRun = <A extends Action.Any, E, R>(
790
901
  plan: Plan.Plan<A, Plan.Coverage>,
791
902
  resolved: Resolved<E, R>,
903
+ observation: Observation<R>,
792
904
  options: ControlOptions,
793
905
  subscribe: Subscribe | undefined,
794
906
  retain: Retain,
795
907
  ): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
796
908
  Effect.gen(function* () {
797
909
  const outcomes = new Map<string, Outcome<E>>();
798
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
910
+ const control = yield* makeControl(options, subscribe);
911
+ const { halt, stop, runPhase } = control;
799
912
  let failedAt: string | undefined;
800
913
 
801
- /** Runs a prepare phase in the occurrence's scope and records what it predicts. */
802
- const prepare = (id: string, handler: Internal<E, R>) => {
803
- const end = (outcome: Outcome<E>) => {
804
- outcomes.set(id, outcome);
805
-
806
- return exitOf(outcome);
807
- };
808
- const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
809
- Effect.gen(function* () {
810
- const preparation = yield* runPhase(handler.prepare(scope), unsettled);
811
- const stopped = unsuccessful("prepare", preparation, stop);
812
- if (stopped !== undefined) return end(stopped);
813
- if (preparation._tag !== "Done") return Exit.void;
814
- if (Exit.isFailure(preparation.exit)) {
815
- failedAt = id;
816
-
817
- return end({
818
- _tag: "PreparationFailed",
819
- ...failureOf(preparation.exit.cause),
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);
918
+
919
+ return emitter.settled(occurrence);
920
+ };
921
+
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);
927
+
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
+ );
820
959
  });
821
- }
822
- // A dry run never applies: the prepared value is discarded.
823
- const step = preparation.exit.value;
824
-
825
- return end(
826
- step._tag === "Skip"
827
- ? { _tag: "WouldSkip", reason: step.reason }
828
- : {
829
- _tag: "WouldExecute",
830
- evaluated: true,
831
- performer: handler.performer,
832
- },
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
+ });
978
+
979
+ return Effect.andThen(
980
+ inScope(retain, id, use, onCleanupFailure),
981
+ emitter.settled(occurrence),
833
982
  );
834
- });
835
- const onCleanupFailure = (cause: Cause.Cause<never>) =>
836
- Effect.suspend(() => {
837
- const outcome = outcomes.get(id);
838
- if (outcome?._tag === "Interrupted") {
839
- return logCleanupFailure({ occurrence: id })(cause);
840
- }
841
- failedAt ??= id;
842
- outcomes.set(id, {
843
- _tag: "PreparationFailed",
844
- ...failureOf(
845
- outcome?._tag === "PreparationFailed"
846
- ? Cause.combine(outcome.cause, cause)
847
- : cause,
848
- ),
849
- });
983
+ };
850
984
 
851
- return Effect.void;
852
- });
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);
853
992
 
854
- return inScope(retain, id, use, onCleanupFailure);
855
- };
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
+ }
856
1004
 
857
- /** Returns whether the node would or might change state. */
858
- const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
859
- Effect.gen(function* () {
860
- if (node._tag === "Sequence") {
861
- let current = dirty;
862
- for (const child of node.children) current = yield* visit(child, current);
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
+ });
863
1013
 
864
- return current;
865
- }
866
- if (node._tag === "Parallel") {
867
- // Branches are independent: each starts from the state before the group.
868
- // They are evaluated one at a time so the report is deterministic.
869
- let changed = dirty;
870
- for (const branch of node.branches)
871
- changed = (yield* visit(branch, dirty)) || changed;
872
-
873
- return changed;
874
- }
1014
+ return true;
1015
+ }
1016
+ if (!handler.prepares) {
1017
+ yield* settle(node, {
1018
+ _tag: "WouldExecute",
1019
+ evaluated: false,
1020
+ performer: handler.performer,
1021
+ });
875
1022
 
876
- const handler = resolved.get(node.id);
877
- if (handler === undefined || halt.reason !== undefined) return dirty;
878
- if (failedAt !== undefined) {
879
- outcomes.set(node.id, {
880
- _tag: "Undetermined",
881
- reason: `Execution would stop at the failed preparation of "${failedAt}".`,
882
- performer: handler.performer,
883
- });
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
+ });
884
1031
 
885
- return true;
886
- }
887
- if (!handler.prepares) {
888
- outcomes.set(node.id, {
889
- _tag: "WouldExecute",
890
- evaluated: false,
891
- performer: handler.performer,
892
- });
1032
+ return true;
1033
+ }
893
1034
 
894
- return true;
895
- }
896
- if (dirty) {
897
- outcomes.set(node.id, {
898
- _tag: "Undetermined",
899
- reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
900
- performer: handler.performer,
1035
+ yield* prepare(node, handler);
1036
+
1037
+ return outcomes.get(node.id)?._tag !== "WouldSkip";
901
1038
  });
902
1039
 
903
- 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);
904
1049
  }
905
1050
 
906
- yield* prepare(node.id, handler);
907
-
908
- return outcomes.get(node.id)?._tag !== "WouldSkip";
909
- });
910
-
911
- // Later migrations conservatively depend on every earlier migration.
912
- let dirty = false;
913
- for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
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
+ ),
1065
+ });
1066
+ }
914
1067
 
915
- if (halt.reason !== undefined && halt.reason !== "failure") {
916
- return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
917
- }
1068
+ const status = failedAt === undefined ? "would-complete" : "would-fail";
1069
+ yield* emitter.runFinished(status);
918
1070
 
919
- return report(
920
- plan,
921
- "dry-run",
922
- failedAt === undefined ? "would-complete" : "would-fail",
923
- outcomes,
924
- false,
1071
+ return report(plan, "dry-run", status, outcomes, false, emitter.failures);
1072
+ }),
925
1073
  );
926
1074
  });
927
1075
 
@@ -930,20 +1078,29 @@ const run = <
930
1078
  C extends Plan.Coverage,
931
1079
  H extends Handler.Any,
932
1080
  I extends Interaction.Any,
1081
+ O extends Observer.Any,
933
1082
  >(
934
1083
  plan: Plan.Plan<A, C>,
935
- options: Options<H, I>,
1084
+ options: Options<H, I, O>,
936
1085
  subscribe: Subscribe | undefined,
937
1086
  retain: Retain,
938
- ): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I>> => {
939
- // Handlers and interactions are covariant in their errors and services, and
940
- // `Errors<H, I>` and `Requirements<H, I>` collect them from each handler in `H` and
941
- // from `I`, so every handler and the interaction fit these shapes. From here on the
942
- // compiler checks both channels.
943
- const handlers: ReadonlyArray<Internal<Errors<H, I>, Requirements<H, I>>> =
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>>> =
944
1097
  options.handlers ?? [];
945
- const interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I>> | undefined =
1098
+ const interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I, O>> | undefined =
946
1099
  options.interaction;
1100
+ const observation: Observation<Requirements<H, I, O>> = {
1101
+ observers: options.observers ?? [],
1102
+ runId: options.runId,
1103
+ };
947
1104
 
948
1105
  return Effect.gen(function* () {
949
1106
  const checked = coverage(plan, handlers);
@@ -961,7 +1118,7 @@ const run = <
961
1118
  }
962
1119
 
963
1120
  if (options.dryRun === true) {
964
- return yield* dryRun(plan, checked.resolved, options, subscribe, retain);
1121
+ return yield* dryRun(plan, checked.resolved, observation, options, subscribe, retain);
965
1122
  }
966
1123
 
967
1124
  // Nobody can answer for manual work, so the run must not start and stop halfway.
@@ -981,7 +1138,15 @@ const run = <
981
1138
  });
982
1139
  }
983
1140
 
984
- return yield* execute(plan, checked.resolved, interaction, options, subscribe, retain);
1141
+ return yield* execute(
1142
+ plan,
1143
+ checked.resolved,
1144
+ interaction,
1145
+ observation,
1146
+ options,
1147
+ subscribe,
1148
+ retain,
1149
+ );
985
1150
  });
986
1151
  };
987
1152
 
@@ -999,36 +1164,39 @@ const run = <
999
1164
  *
1000
1165
  * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
1001
1166
  * signal passed to Promise callbacks. The effect then ends as interrupted, without a
1002
- * report.
1167
+ * report. Observers receive a final `RunFinished` event without a report, delivered
1168
+ * within `settleTimeout`.
1003
1169
  *
1004
- * @since @next
1170
+ * @since 0.0.1
1005
1171
  */
1006
1172
  export const effect = <
1007
1173
  A extends Action.Any,
1008
1174
  C extends Plan.Coverage,
1009
1175
  H extends Handler.Any = never,
1010
1176
  I extends Interaction.Any = never,
1177
+ O extends Observer.Any = never,
1011
1178
  >(
1012
1179
  plan: Plan.Plan<A, C>,
1013
- options: Options<H, I> & CoverageCheck<A, H, C>,
1014
- ): Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>>, Requirements<H, I>> =>
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>> =>
1015
1182
  run(plan, options, undefined, () => {});
1016
1183
 
1017
1184
  type ServicesOption<R, LE> = [R] extends [never]
1018
1185
  ? {
1019
- /** Handlers and interactions without Effect services need none. */
1186
+ /** Handlers, interactions, and observers without Effect services need none. */
1020
1187
  readonly services?: Context.Context<never> | Layer.Layer<never, LE>;
1021
1188
  }
1022
1189
  : {
1023
- /** Supplies the Effect services of the handlers and the interaction. */
1190
+ /** Supplies the Effect services of the handlers, the interaction, and the observers. */
1024
1191
  readonly services: Context.Context<R> | Layer.Layer<R, LE>;
1025
1192
  };
1026
1193
 
1027
- /** @since @next */
1028
- export type PromiseOptions<H extends Handler.Any, I extends Interaction.Any = never> = Options<
1029
- H,
1030
- I
1031
- > & {
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> & {
1032
1200
  /**
1033
1201
  * Explicit cancellation. Aborting stops admission, interrupts running actions and
1034
1202
  * pending confirmations, and rejects with `ExecutionInterrupted` and the partial
@@ -1051,17 +1219,21 @@ export type PromiseOptions<H extends Handler.Any, I extends Interaction.Any = ne
1051
1219
  * until it settles, possibly forever, and close in that order. A cleanup failure after
1052
1220
  * the Promise resolved is logged through Effect.
1053
1221
  *
1054
- * @since @next
1222
+ * @since 0.0.1
1055
1223
  */
1056
1224
  export const runPromise = <
1057
1225
  A extends Action.Any,
1058
1226
  C extends Plan.Coverage,
1059
1227
  H extends Handler.Any = never,
1060
1228
  I extends Interaction.Any = never,
1229
+ // After `LE`, so explicit type arguments written for earlier releases keep their meaning.
1061
1230
  LE = never,
1231
+ O extends Observer.Any = never,
1062
1232
  >(
1063
1233
  plan: Plan.Plan<A, C>,
1064
- options: PromiseOptions<H, I> & ServicesOption<Requirements<H, I>, LE> & CoverageCheck<A, H, C>,
1234
+ options: PromiseOptions<H, I, O> &
1235
+ ServicesOption<Requirements<H, I, O>, LE> &
1236
+ CoverageCheck<A, H, C>,
1065
1237
  ): Promise<Report<A, Errors<H, I>>> => {
1066
1238
  const { signal } = options;
1067
1239
  const notStarted = () =>