deltafold 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,14 +7,17 @@ import {
7
7
  Effect,
8
8
  Equal,
9
9
  Exit,
10
+ Fiber,
10
11
  Layer,
11
12
  Option,
13
+ Scope,
12
14
  } from "effect";
13
15
 
14
16
  import type * as Action from "../../foundation/action.ts";
15
17
  import type * as Plan from "../../foundation/plan.ts";
16
18
  import type { Node, Occurrence } from "../../foundation/plan.ts";
17
19
  import * as Handler from "./handler.ts";
20
+ import type * as Interaction from "./interaction.ts";
18
21
  import { SettlementReference } from "./settlement.ts";
19
22
 
20
23
  /**
@@ -23,8 +26,20 @@ import { SettlementReference } from "./settlement.ts";
23
26
  * @since @next
24
27
  */
25
28
  export type Outcome<E = unknown> =
26
- | { readonly _tag: "Completed" }
29
+ | { readonly _tag: "Completed"; readonly performer: "automated" }
30
+ | {
31
+ readonly _tag: "Completed";
32
+ readonly performer: "manual";
33
+ /**
34
+ * What supports completion. `asserted`: the person said so and nothing checked
35
+ * it. `verified`: the person said so and the handler's `verify` check passed.
36
+ * Neither proves how the work was done.
37
+ */
38
+ readonly confirmation: "asserted" | "verified";
39
+ }
27
40
  | { readonly _tag: "Skipped"; readonly reason: string }
41
+ /** The person asked to confirm manual work answered that it is not done. */
42
+ | { readonly _tag: "Declined" }
28
43
  | {
29
44
  readonly _tag: "Failed";
30
45
  readonly phase: Handler.Phase;
@@ -46,11 +61,24 @@ export type Outcome<E = unknown> =
46
61
  }
47
62
  /** Not started because execution stopped first. */
48
63
  | { readonly _tag: "Unattempted" }
49
- | { readonly _tag: "WouldExecute"; readonly evaluated: boolean }
64
+ /**
65
+ * `evaluated`: whether a prepare phase ran and decided to apply. A `manual` occurrence
66
+ * would wait for a person; a dry run never asks.
67
+ */
68
+ | {
69
+ readonly _tag: "WouldExecute";
70
+ readonly evaluated: boolean;
71
+ readonly performer: Handler.Performer;
72
+ }
50
73
  | { readonly _tag: "WouldSkip"; readonly reason: string }
51
- | { readonly _tag: "Undetermined"; readonly reason: string }
52
74
  | {
53
- readonly _tag: "PreconditionFailed";
75
+ readonly _tag: "Undetermined";
76
+ readonly reason: string;
77
+ /** A `manual` occurrence would wait for a person if it executes. */
78
+ readonly performer: Handler.Performer;
79
+ }
80
+ | {
81
+ readonly _tag: "PreparationFailed";
54
82
  readonly error: E | undefined;
55
83
  readonly cause: Cause.Cause<E>;
56
84
  };
@@ -77,7 +105,10 @@ export type Report<A extends Action.Any = Action.Any, E = unknown> = {
77
105
  readonly route: string;
78
106
  /** Every occurrence in plan order. */
79
107
  readonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;
80
- /** Whether any action body started. A started body may have partially changed state. */
108
+ /**
109
+ * Whether any apply phase started or any person was asked to do manual work. Either
110
+ * may have partially changed state.
111
+ */
81
112
  readonly bodiesStarted: boolean;
82
113
  /** Progress is not persisted. Rerunning the plan repeats completed actions. */
83
114
  readonly persistence: "none";
@@ -106,10 +137,10 @@ export type CoverageIssue = {
106
137
  const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
107
138
 
108
139
  /**
109
- * Handler coverage failed before any precondition or body ran. Every occurrence needs
110
- * exactly one handler, for the same action definition: the same identifier, kind, and
111
- * payload. For an occurrence that a rule produced, the issue names the rule and the
112
- * occurrences it replaced.
140
+ * Handler coverage failed before any handler phase ran. Every occurrence needs exactly
141
+ * one handler, for the same action definition: the same identifier, kind, and payload.
142
+ * For an occurrence that a rule produced, the issue names the rule and the occurrences
143
+ * it replaced.
113
144
  *
114
145
  * @since @next
115
146
  */
@@ -127,10 +158,44 @@ export class HandlerCoverageError<A extends Action.Any = Action.Any> extends Han
127
158
  }
128
159
  }
129
160
 
161
+ const InteractionUnavailableBase = Data.TaggedError("InteractionUnavailable");
162
+
163
+ /**
164
+ * The plan has manual handlers, and the run has no `interaction` to ask a person. The
165
+ * run fails before any handler phase or prompt.
166
+ *
167
+ * @since @next
168
+ */
169
+ export class InteractionUnavailable<
170
+ A extends Action.Any = Action.Any,
171
+ > extends InteractionUnavailableBase<{
172
+ /** The occurrences that a manual handler covers, in plan order. */
173
+ readonly occurrences: ReadonlyArray<Occurrence<A>>;
174
+ readonly report: Report<A, never>;
175
+ }> {
176
+ override get message() {
177
+ return `No interaction is available to confirm manual work for ${this.occurrences
178
+ .map((occurrence) => `"${occurrence.id}" (${occurrence.action.description})`)
179
+ .join(
180
+ ", ",
181
+ )}. Supply the \`interaction\` option, or bind automated handlers to these actions.`;
182
+ }
183
+ }
184
+
185
+ const listIds = (entries: ReadonlyArray<OccurrenceReport>) =>
186
+ entries
187
+ .map((entry) =>
188
+ entry.outcome._tag === "Failed"
189
+ ? `"${entry.occurrence.id}" (${entry.outcome.phase})`
190
+ : `"${entry.occurrence.id}"`,
191
+ )
192
+ .join(", ");
193
+
130
194
  const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
131
195
 
132
196
  /**
133
- * An occurrence failed. Execution stopped admitting new actions; started ones settled.
197
+ * An occurrence failed, or a person declined manual work. Execution stopped admitting
198
+ * new actions; started ones settled.
134
199
  *
135
200
  * @since @next
136
201
  */
@@ -139,12 +204,23 @@ export class ExecutionFailed<
139
204
  E = unknown,
140
205
  > extends ExecutionFailedBase<{
141
206
  readonly failures: ReadonlyArray<OccurrenceReport<A, E>>;
207
+ /** Manual occurrences that a person declined. */
208
+ readonly declined: ReadonlyArray<OccurrenceReport<A, E>>;
142
209
  readonly report: Report<A, E>;
143
210
  }> {
144
211
  override get message() {
145
- return `Execution failed at ${this.failures
146
- .map((failure) => `"${failure.occurrence.id}"`)
147
- .join(", ")}. Completed actions were not rolled back.`;
212
+ const parts = [
213
+ ...(this.failures.length === 0
214
+ ? []
215
+ : [`Execution failed at ${listIds(this.failures)}.`]),
216
+ ...(this.declined.length === 0
217
+ ? []
218
+ : [
219
+ `Manual work was declined at ${listIds(this.declined)}, which stopped the run.`,
220
+ ]),
221
+ ];
222
+
223
+ return `${parts.join(" ")} Completed actions were not rolled back.`;
148
224
  }
149
225
  }
150
226
 
@@ -193,6 +269,7 @@ export class ExecutionInterrupted<
193
269
  /** @since @next */
194
270
  export type ExecutionError<A extends Action.Any, E> =
195
271
  | HandlerCoverageError<A>
272
+ | InteractionUnavailable<A>
196
273
  | ExecutionFailed<A, E>
197
274
  | ExecutionInterrupted<A, E>;
198
275
 
@@ -224,27 +301,37 @@ type CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [
224
301
  *
225
302
  * @since @next
226
303
  */
227
- export type Errors<H> = Handler.Error<H>;
304
+ export type Errors<H, I = never> = Handler.Error<H> | Interaction.Error<I>;
228
305
 
229
306
  /**
230
- * Effect services an execution requires: the services of its handlers.
307
+ * Effect services an execution requires: the services of its handlers and of its
308
+ * interaction.
231
309
  *
232
310
  * @since @next
233
311
  */
234
- export type Requirements<H> = Handler.Services<H>;
312
+ export type Requirements<H, I = never> = Handler.Services<H> | Interaction.Services<I>;
235
313
 
236
314
  /** @since @next */
237
- export type Options<H extends Handler.Any> = {
315
+ export type Options<H extends Handler.Any, I extends Interaction.Any = never> = {
238
316
  readonly handlers?: ReadonlyArray<H>;
239
317
  /**
240
- * Evaluate preconditions without running any action body. A precondition that may
241
- * depend on an earlier action is reported `Undetermined`, because the dry run does not
242
- * apply that action.
318
+ * Asks a person to confirm the work of manual handlers. A run whose plan has manual
319
+ * handlers fails with `InteractionUnavailable` before it starts when this is absent.
320
+ * A dry run never asks and does not need it.
321
+ */
322
+ readonly interaction?: I;
323
+ /**
324
+ * Run prepare phases without running any apply phase. A prepare phase that may
325
+ * depend on an earlier action is reported `Undetermined`, because the dry run does
326
+ * not apply that action.
243
327
  */
244
328
  readonly dryRun?: boolean;
245
329
  /**
246
- * Per-occurrence limit for a precondition or body. Exceeding it interrupts that action
247
- * and stops admitting new ones. It applies to dry-run preconditions too.
330
+ * Limit for each phase of an occurrence: the prepare phase and the apply phase each
331
+ * get the full limit, and so does the verification of manual work. Exceeding it
332
+ * interrupts that action and stops admitting new ones. It applies to dry-run prepare
333
+ * phases too. It never limits the wait for a person to confirm manual work; cancel
334
+ * the run to end that wait.
248
335
  */
249
336
  readonly timeout?: Duration.Input;
250
337
  /**
@@ -336,6 +423,19 @@ const failureOf = <E>(cause: Cause.Cause<E>) => ({
336
423
  cause,
337
424
  });
338
425
 
426
+ /** The exit an occurrence's scope closes with, so finalizers see how it ended. */
427
+ const exitOf = <E>(outcome: Outcome<E> | undefined): Exit.Exit<void, E> => {
428
+ switch (outcome?._tag) {
429
+ case "Failed":
430
+ case "PreparationFailed":
431
+ return Exit.failCause(outcome.cause);
432
+ case "Interrupted":
433
+ return Exit.interrupt();
434
+ default:
435
+ return Exit.void;
436
+ }
437
+ };
438
+
339
439
  const forEachBranch = <R>(
340
440
  branches: ReadonlyArray<Node>,
341
441
  concurrency: Action.Concurrency,
@@ -345,6 +445,12 @@ const forEachBranch = <R>(
345
445
  /** Registers a callback that cancels the execution. Only `runPromise` uses it. */
346
446
  type Subscribe = (cancel: () => void) => void;
347
447
 
448
+ /**
449
+ * Receives the fiber that closes an occurrence scope after an interrupted Promise
450
+ * settles, so the caller can keep the services it built open until then.
451
+ */
452
+ type Retain = (fiber: Fiber.Fiber<void>) => void;
453
+
348
454
  type StopReason = "failure" | InterruptReason;
349
455
 
350
456
  type PhaseResult<T, E> =
@@ -357,6 +463,16 @@ type PhaseResult<T, E> =
357
463
 
358
464
  type ControlOptions = Pick<Options<never>, "timeout" | "settleTimeout">;
359
465
 
466
+ /** Waiting for a person is `untimed`: only cancellation ends it. */
467
+ type Timing = "timed" | "untimed";
468
+
469
+ /**
470
+ * Logs a cleanup failure that the report cannot carry, with the occurrence or the
471
+ * services layer that owned the resources.
472
+ */
473
+ const logCleanupFailure = (owner: Record<string, string>) => (cause: Cause.Cause<unknown>) =>
474
+ Effect.logError("deltafold: cleanup failed", cause).pipe(Effect.annotateLogs(owner));
475
+
360
476
  /** Admission state, cancellation, and timeouts shared by real and dry runs. */
361
477
  const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>
362
478
  Effect.gen(function* () {
@@ -367,29 +483,38 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
367
483
  const stop = (reason: StopReason) => {
368
484
  halt.reason ??= reason;
369
485
  };
486
+ // A failure can be the first stop reason, so cancellation is also tracked on its own.
487
+ let cancellationArrived = false;
370
488
  subscribe?.(() => {
489
+ cancellationArrived = true;
371
490
  stop("cancelled");
372
491
  Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
373
492
  });
374
493
 
375
- /** Runs one precondition or body, racing it against cancellation and the timeout. */
494
+ /**
495
+ * Runs one phase, racing it against cancellation and its own timeout. An
496
+ * interrupted Promise that outlives the settlement grace period goes to `unsettled`.
497
+ */
376
498
  const runPhase = <T, E, R>(
377
499
  work: Effect.Effect<T, E, R>,
500
+ unsettled: Array<Promise<void>>,
501
+ timing: Timing = "timed",
378
502
  ): Effect.Effect<PhaseResult<T, E>, never, R> =>
379
503
  Effect.gen(function* () {
380
504
  let settled = true;
381
505
  const tracked = work.pipe(
382
506
  Effect.provideService(SettlementReference, {
383
507
  grace: settleTimeout,
384
- record: (value) => {
385
- settled = value;
508
+ unsettled: (promise) => {
509
+ settled = false;
510
+ unsettled.push(promise);
386
511
  },
387
512
  }),
388
513
  );
389
514
  const stopSignals: Array<Effect.Effect<"cancelled" | "timeout">> = [
390
515
  Deferred.await(cancelled),
391
516
  ];
392
- if (options.timeout !== undefined) {
517
+ if (options.timeout !== undefined && timing === "timed") {
393
518
  stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout" as const));
394
519
  }
395
520
  const result = yield* Effect.raceFirst(
@@ -407,9 +532,48 @@ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined)
407
532
  return { _tag: "Interrupted" as const, reason: result.reason, settled };
408
533
  });
409
534
 
410
- return { halt, stop, runPhase };
535
+ return { halt, stop, runPhase, isCancelled: () => cancellationArrived };
411
536
  });
412
537
 
538
+ /**
539
+ * Runs one occurrence in its own scope, which both phases share. `use` returns the
540
+ * exit to close the scope with. The scope closes as soon as the occurrence ends, and
541
+ * a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not
542
+ * settled, the scope stays open until it does, possibly forever; a failing
543
+ * finalizer is then logged, because the report may already have been returned.
544
+ */
545
+ const inScope = <E, R>(
546
+ retain: Retain,
547
+ occurrenceId: string,
548
+ use: (
549
+ scope: Scope.Scope,
550
+ unsettled: Array<Promise<void>>,
551
+ ) => Effect.Effect<Exit.Exit<void, E>, never, R>,
552
+ onCleanupFailure: (cause: Cause.Cause<never>) => Effect.Effect<void>,
553
+ ): Effect.Effect<void, never, R> =>
554
+ Effect.uninterruptibleMask((restore) =>
555
+ Effect.gen(function* () {
556
+ const scope = yield* Scope.make();
557
+ const unsettled: Array<Promise<void>> = [];
558
+ const used = yield* Effect.exit(restore(use(scope, unsettled)));
559
+ const end = Exit.isSuccess(used) ? used.value : used;
560
+ if (unsettled.length > 0) {
561
+ const fiber = yield* Effect.forkDetach(
562
+ Effect.promise(() => Promise.all(unsettled)).pipe(
563
+ Effect.andThen(Scope.close(scope, end)),
564
+ Effect.catchCause(logCleanupFailure({ occurrence: occurrenceId })),
565
+ ),
566
+ );
567
+ retain(fiber);
568
+ } else {
569
+ const closed = yield* Effect.exit(Scope.close(scope, end));
570
+ if (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);
571
+ }
572
+
573
+ return yield* used;
574
+ }),
575
+ ).pipe(Effect.asVoid);
576
+
413
577
  const interrupted = <A extends Action.Any, E>(
414
578
  plan: Plan.Plan<A, Plan.Coverage>,
415
579
  mode: Report["mode"],
@@ -422,108 +586,172 @@ const interrupted = <A extends Action.Any, E>(
422
586
  report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
423
587
  });
424
588
 
589
+ /**
590
+ * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
591
+ * handler that interrupted itself stops admission.
592
+ */
593
+ const unsuccessful = <T, E>(
594
+ phase: Handler.Phase,
595
+ result: PhaseResult<T, E>,
596
+ stop: (reason: StopReason) => void,
597
+ ): Outcome<E> | undefined => {
598
+ if (result._tag === "Interrupted") {
599
+ return {
600
+ _tag: "Interrupted",
601
+ phase,
602
+ reason: result.reason,
603
+ settled: result.settled,
604
+ };
605
+ }
606
+ if (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {
607
+ stop("handler");
608
+
609
+ return { _tag: "Interrupted", phase, reason: "handler", settled: true };
610
+ }
611
+
612
+ return undefined;
613
+ };
614
+
425
615
  const execute = <A extends Action.Any, E, R>(
426
616
  plan: Plan.Plan<A, Plan.Coverage>,
427
617
  resolved: Resolved<E, R>,
618
+ interaction: Interaction.Interaction<E, R> | undefined,
428
619
  options: ControlOptions,
429
620
  subscribe: Subscribe | undefined,
621
+ retain: Retain,
430
622
  ): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
431
623
  Effect.gen(function* () {
432
624
  const outcomes = new Map<string, Outcome<E>>();
433
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
625
+ const { halt, stop, runPhase, isCancelled } = yield* makeControl(options, subscribe);
434
626
  let bodiesStarted = false;
435
627
 
436
- const runOccurrence = (occurrence: Occurrence) =>
437
- Effect.gen(function* () {
438
- if (halt.reason !== undefined) return;
439
-
440
- const handler = resolved.get(occurrence.id);
441
- if (handler === undefined) return;
442
-
443
- if (handler.precondition !== undefined) {
444
- const checked = yield* runPhase(handler.precondition);
445
- if (checked._tag === "Interrupted") {
446
- outcomes.set(occurrence.id, {
447
- _tag: "Interrupted",
448
- phase: "precondition",
449
- reason: checked.reason,
450
- settled: checked.settled,
451
- });
452
-
453
- return;
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;
454
664
  }
455
- if (
456
- Exit.isFailure(checked.exit) &&
457
- Cause.hasInterruptsOnly(checked.exit.cause)
458
- ) {
459
- stop("handler");
460
- outcomes.set(occurrence.id, {
461
- _tag: "Interrupted",
462
- phase: "precondition",
463
- reason: "handler",
464
- settled: true,
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");
684
+
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
+ }
694
+
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",
465
716
  });
466
-
467
- return;
468
717
  }
469
- if (Exit.isFailure(checked.exit)) {
470
- stop("failure");
471
- outcomes.set(occurrence.id, {
472
- _tag: "Failed",
473
- phase: "precondition",
474
- ...failureOf(checked.exit.cause),
475
- });
476
718
 
477
- return;
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);
478
738
  }
479
- if (!checked.exit.value) {
480
- outcomes.set(occurrence.id, {
481
- _tag: "Skipped",
482
- reason: handler.skipReason,
483
- });
484
-
485
- return;
486
- }
487
- // The occurrence has started, so a sibling failure lets it finish.
488
- // Cancellation that arrived during the precondition keeps the body from starting.
489
- if (halt.reason === "cancelled") return;
490
- }
491
-
492
- bodiesStarted = true;
493
- const ran = yield* runPhase(handler.body);
494
- if (ran._tag === "Interrupted") {
495
- outcomes.set(occurrence.id, {
496
- _tag: "Interrupted",
497
- phase: "body",
498
- reason: ran.reason,
499
- settled: ran.settled,
500
- });
501
-
502
- return;
503
- }
504
- if (Exit.isFailure(ran.exit) && Cause.hasInterruptsOnly(ran.exit.cause)) {
505
- stop("handler");
506
- outcomes.set(occurrence.id, {
507
- _tag: "Interrupted",
508
- phase: "body",
509
- reason: "handler",
510
- settled: true,
511
- });
512
-
513
- return;
514
- }
515
- if (Exit.isFailure(ran.exit)) {
516
739
  stop("failure");
517
740
  outcomes.set(occurrence.id, {
518
741
  _tag: "Failed",
519
- phase: "body",
520
- ...failureOf(ran.exit.cause),
742
+ phase,
743
+ ...failureOf(
744
+ outcome?._tag === "Failed"
745
+ ? Cause.combine(outcome.cause, cause)
746
+ : cause,
747
+ ),
521
748
  });
522
749
 
523
- return;
524
- }
525
- outcomes.set(occurrence.id, { _tag: "Completed" });
526
- });
750
+ return Effect.void;
751
+ });
752
+
753
+ return inScope(retain, occurrence.id, use, onCleanupFailure);
754
+ };
527
755
 
528
756
  const runNode = (node: Node): Effect.Effect<void, never, R> => {
529
757
  switch (node._tag) {
@@ -550,6 +778,7 @@ const execute = <A extends Action.Any, E, R>(
550
778
 
551
779
  return yield* new ExecutionFailed({
552
780
  failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
781
+ declined: result.occurrences.filter((entry) => entry.outcome._tag === "Declined"),
553
782
  report: result,
554
783
  });
555
784
  }
@@ -562,12 +791,69 @@ const dryRun = <A extends Action.Any, E, R>(
562
791
  resolved: Resolved<E, R>,
563
792
  options: ControlOptions,
564
793
  subscribe: Subscribe | undefined,
794
+ retain: Retain,
565
795
  ): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
566
796
  Effect.gen(function* () {
567
797
  const outcomes = new Map<string, Outcome<E>>();
568
798
  const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
569
799
  let failedAt: string | undefined;
570
800
 
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),
820
+ });
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
+ },
833
+ );
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
+ });
850
+
851
+ return Effect.void;
852
+ });
853
+
854
+ return inScope(retain, id, use, onCleanupFailure);
855
+ };
856
+
571
857
  /** Returns whether the node would or might change state. */
572
858
  const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
573
859
  Effect.gen(function* () {
@@ -592,64 +878,34 @@ const dryRun = <A extends Action.Any, E, R>(
592
878
  if (failedAt !== undefined) {
593
879
  outcomes.set(node.id, {
594
880
  _tag: "Undetermined",
595
- reason: `Execution would stop at the failed precondition of "${failedAt}".`,
881
+ reason: `Execution would stop at the failed preparation of "${failedAt}".`,
882
+ performer: handler.performer,
596
883
  });
597
884
 
598
885
  return true;
599
886
  }
600
- if (handler.precondition === undefined) {
601
- outcomes.set(node.id, { _tag: "WouldExecute", evaluated: false });
602
-
603
- return true;
604
- }
605
- if (dirty) {
887
+ if (!handler.prepares) {
606
888
  outcomes.set(node.id, {
607
- _tag: "Undetermined",
608
- reason: "The precondition depends on earlier actions that a dry run does not apply.",
889
+ _tag: "WouldExecute",
890
+ evaluated: false,
891
+ performer: handler.performer,
609
892
  });
610
893
 
611
894
  return true;
612
895
  }
613
-
614
- const checked = yield* runPhase(handler.precondition);
615
- if (checked._tag === "Interrupted") {
616
- outcomes.set(node.id, {
617
- _tag: "Interrupted",
618
- phase: "precondition",
619
- reason: checked.reason,
620
- settled: checked.settled,
621
- });
622
-
623
- return true;
624
- }
625
- if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
626
- stop("handler");
627
- outcomes.set(node.id, {
628
- _tag: "Interrupted",
629
- phase: "precondition",
630
- reason: "handler",
631
- settled: true,
632
- });
633
-
634
- return true;
635
- }
636
- if (Exit.isFailure(checked.exit)) {
637
- failedAt = node.id;
896
+ if (dirty) {
638
897
  outcomes.set(node.id, {
639
- _tag: "PreconditionFailed",
640
- ...failureOf(checked.exit.cause),
898
+ _tag: "Undetermined",
899
+ reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
900
+ performer: handler.performer,
641
901
  });
642
902
 
643
903
  return true;
644
904
  }
645
- if (!checked.exit.value) {
646
- outcomes.set(node.id, { _tag: "WouldSkip", reason: handler.skipReason });
647
905
 
648
- return false;
649
- }
650
- outcomes.set(node.id, { _tag: "WouldExecute", evaluated: true });
906
+ yield* prepare(node.id, handler);
651
907
 
652
- return true;
908
+ return outcomes.get(node.id)?._tag !== "WouldSkip";
653
909
  });
654
910
 
655
911
  // Later migrations conservatively depend on every earlier migration.
@@ -669,15 +925,25 @@ const dryRun = <A extends Action.Any, E, R>(
669
925
  );
670
926
  });
671
927
 
672
- const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.Any>(
928
+ const run = <
929
+ A extends Action.Any,
930
+ C extends Plan.Coverage,
931
+ H extends Handler.Any,
932
+ I extends Interaction.Any,
933
+ >(
673
934
  plan: Plan.Plan<A, C>,
674
- options: Options<H>,
935
+ options: Options<H, I>,
675
936
  subscribe: Subscribe | undefined,
676
- ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> => {
677
- // Handlers are covariant in their errors and services, and `Errors<H>` and
678
- // `Requirements<H>` collect them from each handler in `H`, so every handler fits this
679
- // shape. From here on the compiler checks both channels.
680
- const handlers: ReadonlyArray<Internal<Errors<H>, Requirements<H>>> = options.handlers ?? [];
937
+ 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>>> =
944
+ options.handlers ?? [];
945
+ const interaction: Interaction.Interaction<Errors<H, I>, Requirements<H, I>> | undefined =
946
+ options.interaction;
681
947
 
682
948
  return Effect.gen(function* () {
683
949
  const checked = coverage(plan, handlers);
@@ -694,17 +960,42 @@ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.An
694
960
  });
695
961
  }
696
962
 
697
- return options.dryRun === true
698
- ? yield* dryRun(plan, checked.resolved, options, subscribe)
699
- : yield* execute(plan, checked.resolved, options, subscribe);
963
+ if (options.dryRun === true) {
964
+ return yield* dryRun(plan, checked.resolved, options, subscribe, retain);
965
+ }
966
+
967
+ // Nobody can answer for manual work, so the run must not start and stop halfway.
968
+ const manual = plan.occurrences.filter(
969
+ (occurrence) => checked.resolved.get(occurrence.id)?.performer === "manual",
970
+ );
971
+ if (manual.length > 0 && interaction === undefined) {
972
+ return yield* new InteractionUnavailable({
973
+ occurrences: manual,
974
+ report: report(
975
+ plan,
976
+ "execute",
977
+ "not-started",
978
+ new Map<string, Outcome<never>>(),
979
+ false,
980
+ ),
981
+ });
982
+ }
983
+
984
+ return yield* execute(plan, checked.resolved, interaction, options, subscribe, retain);
700
985
  });
701
986
  };
702
987
 
703
988
  /**
704
- * Runs a plan as an Effect. Coverage is checked before any precondition or body runs.
705
- * Steps are sequential barriers; parallel groups run their branches concurrently. On
706
- * failure, no new action starts, and actions already running settle before the effect
707
- * fails with the partial report.
989
+ * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,
990
+ * are checked before any handler phase runs. Steps
991
+ * are sequential barriers; parallel groups run their branches concurrently. On failure,
992
+ * no new action starts, and actions already running settle before the effect fails
993
+ * with the partial report.
994
+ *
995
+ * Each occurrence has its own scope, shared by its phases and closed when it ends. An
996
+ * interrupted Promise that has not settled keeps its occurrence's scope open until it
997
+ * settles, after the effect has ended. Services that the caller provides stay the
998
+ * caller's to release.
708
999
  *
709
1000
  * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
710
1001
  * signal passed to Promise callbacks. The effect then ends as interrupted, without a
@@ -716,41 +1007,49 @@ export const effect = <
716
1007
  A extends Action.Any,
717
1008
  C extends Plan.Coverage,
718
1009
  H extends Handler.Any = never,
1010
+ I extends Interaction.Any = never,
719
1011
  >(
720
1012
  plan: Plan.Plan<A, C>,
721
- options: Options<H> & CoverageCheck<A, H, C>,
722
- ): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> =>
723
- run(plan, options, undefined);
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>> =>
1015
+ run(plan, options, undefined, () => {});
724
1016
 
725
1017
  type ServicesOption<R, LE> = [R] extends [never]
726
1018
  ? {
727
- /** Handlers without Effect services need none. */
1019
+ /** Handlers and interactions without Effect services need none. */
728
1020
  readonly services?: Context.Context<never> | Layer.Layer<never, LE>;
729
1021
  }
730
1022
  : {
731
- /** Supplies the handlers' Effect services. */
1023
+ /** Supplies the Effect services of the handlers and the interaction. */
732
1024
  readonly services: Context.Context<R> | Layer.Layer<R, LE>;
733
1025
  };
734
1026
 
735
1027
  /** @since @next */
736
- export type PromiseOptions<H extends Handler.Any> = Options<H> & {
1028
+ export type PromiseOptions<H extends Handler.Any, I extends Interaction.Any = never> = Options<
1029
+ H,
1030
+ I
1031
+ > & {
737
1032
  /**
738
- * Explicit cancellation. Aborting stops admission, interrupts running actions, and
739
- * rejects with `ExecutionInterrupted` and the partial report.
1033
+ * Explicit cancellation. Aborting stops admission, interrupts running actions and
1034
+ * pending confirmations, and rejects with `ExecutionInterrupted` and the partial
1035
+ * report.
740
1036
  */
741
1037
  readonly signal?: AbortSignal;
742
1038
  };
743
1039
 
744
1040
  /**
745
1041
  * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
746
- * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
1042
+ * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying
1043
+ * the partial report.
747
1044
  * Building a supplied services layer can also reject with the layer's own error,
748
1045
  * without a report.
749
1046
  *
750
- * A services layer is built for this run and finalized when the run ends. A services
751
- * context stays owned by the caller. A Promise callback that ignores its signal can keep
752
- * running after cancellation or a timeout, beyond `settleTimeout`, and so after the
753
- * run's layer resources are finalized; the report marks it as possibly still running.
1047
+ * A services layer is built for this run. A services context stays owned by the
1048
+ * caller. A Promise callback that ignores its signal can keep running after
1049
+ * cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly
1050
+ * still running. Its occurrence's scope and the run's services layer then stay open
1051
+ * until it settles, possibly forever, and close in that order. A cleanup failure after
1052
+ * the Promise resolved is logged through Effect.
754
1053
  *
755
1054
  * @since @next
756
1055
  */
@@ -758,11 +1057,12 @@ export const runPromise = <
758
1057
  A extends Action.Any,
759
1058
  C extends Plan.Coverage,
760
1059
  H extends Handler.Any = never,
1060
+ I extends Interaction.Any = never,
761
1061
  LE = never,
762
1062
  >(
763
1063
  plan: Plan.Plan<A, C>,
764
- options: PromiseOptions<H> & ServicesOption<Requirements<H>, LE> & CoverageCheck<A, H, C>,
765
- ): Promise<Report<A, Errors<H>>> => {
1064
+ options: PromiseOptions<H, I> & ServicesOption<Requirements<H, I>, LE> & CoverageCheck<A, H, C>,
1065
+ ): Promise<Report<A, Errors<H, I>>> => {
766
1066
  const { signal } = options;
767
1067
  const notStarted = () =>
768
1068
  new ExecutionInterrupted({
@@ -771,7 +1071,7 @@ export const runPromise = <
771
1071
  plan,
772
1072
  options.dryRun === true ? "dry-run" : "execute",
773
1073
  "interrupted",
774
- new Map<string, Outcome<Errors<H>>>(),
1074
+ new Map<string, Outcome<Errors<H, I>>>(),
775
1075
  false,
776
1076
  ),
777
1077
  });
@@ -793,16 +1093,45 @@ export const runPromise = <
793
1093
  cancelRun = cancel;
794
1094
  if (signal.aborted) cancel();
795
1095
  };
796
- const program = run(plan, options, subscribe);
1096
+ const retained: Array<Fiber.Fiber<void>> = [];
1097
+ const program = run(plan, options, subscribe, (fiber) => retained.push(fiber));
797
1098
  const services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;
798
1099
  const provided =
799
1100
  services === undefined
800
1101
  ? program
801
1102
  : Context.isContext(services)
802
1103
  ? Effect.provideContext(program, services)
803
- : // runPromise is the entry point: the caller's layer is built for this one run.
804
- // oxlint-disable-next-line effecttsgo/strict-effect-provide
805
- Effect.provide(program, services);
1104
+ : // runPromise is the entry point: the caller's layer is built for this one run,
1105
+ // in a scope that outlives the run while retained occurrence scopes are open.
1106
+ Effect.uninterruptibleMask((restore) =>
1107
+ Effect.gen(function* () {
1108
+ const scope = yield* Scope.make();
1109
+ const built = yield* Effect.exit(
1110
+ restore(Layer.buildWithScope(services, scope)),
1111
+ );
1112
+ if (Exit.isFailure(built)) {
1113
+ yield* Scope.close(scope, built);
1114
+
1115
+ return yield* built;
1116
+ }
1117
+ const exit = yield* Effect.exit(
1118
+ restore(Effect.provideContext(program, built.value)),
1119
+ );
1120
+ if (retained.length === 0) yield* Scope.close(scope, exit);
1121
+ else {
1122
+ yield* Effect.forkDetach(
1123
+ Fiber.awaitAll(retained).pipe(
1124
+ Effect.andThen(Scope.close(scope, exit)),
1125
+ Effect.catchCause(
1126
+ logCleanupFailure({ owner: "services layer" }),
1127
+ ),
1128
+ ),
1129
+ );
1130
+ }
1131
+
1132
+ return yield* exit;
1133
+ }),
1134
+ );
806
1135
  const cancellable =
807
1136
  signal === undefined
808
1137
  ? provided
@@ -815,7 +1144,7 @@ export const runPromise = <
815
1144
  // `ServicesOption` requires services that cover every requirement. A layer that
816
1145
  // fails to build rejects with its own error.
817
1146
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion
818
- cancellable as Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>> | LE>,
1147
+ cancellable as Effect.Effect<Report<A, Errors<H, I>>, ExecutionError<A, Errors<H, I>> | LE>,
819
1148
  )
820
1149
  .finally(() => signal?.removeEventListener("abort", onAbort))
821
1150
  .then((exit) => {