deltafold 0.0.0 → 0.0.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 (57) hide show
  1. package/README.md +274 -4
  2. package/dist/changelog.d.ts +116 -0
  3. package/dist/changelog.d.ts.map +1 -0
  4. package/dist/changelog.js +304 -0
  5. package/dist/changelog.js.map +1 -0
  6. package/dist/document-BZcZo9nr.js +171 -0
  7. package/dist/document-BZcZo9nr.js.map +1 -0
  8. package/dist/document-DWHsgywm.d.ts +257 -0
  9. package/dist/document-DWHsgywm.d.ts.map +1 -0
  10. package/dist/html.d.ts +8 -0
  11. package/dist/html.d.ts.map +1 -0
  12. package/dist/html.js +13 -0
  13. package/dist/html.js.map +1 -0
  14. package/dist/index.d.ts +378 -1
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +2058 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/markdown.d.ts +8 -0
  19. package/dist/markdown.d.ts.map +1 -0
  20. package/dist/markdown.js +16 -0
  21. package/dist/markdown.js.map +1 -0
  22. package/dist/mdast-DiRsYwPU.js +108 -0
  23. package/dist/mdast-DiRsYwPU.js.map +1 -0
  24. package/dist/package-BfBYnaCz.d.ts +1125 -0
  25. package/dist/package-BfBYnaCz.d.ts.map +1 -0
  26. package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
  27. package/package.json +13 -1
  28. package/src/features/documents/changelog.ts +450 -0
  29. package/src/features/documents/document.ts +357 -0
  30. package/src/features/documents/index.ts +4 -0
  31. package/src/features/documents/public-document.ts +31 -0
  32. package/src/features/documents/sections.ts +44 -0
  33. package/src/features/execution/executor.ts +826 -0
  34. package/src/features/execution/handler.ts +257 -0
  35. package/src/features/execution/settlement.ts +49 -0
  36. package/src/features/package.ts +32 -0
  37. package/src/features/planning/guide.ts +56 -0
  38. package/src/features/planning/history.ts +174 -0
  39. package/src/features/planning/identifiers.ts +43 -0
  40. package/src/features/planning/resolve-error.ts +201 -0
  41. package/src/features/planning/resolve.ts +724 -0
  42. package/src/features/planning/rewrite.ts +331 -0
  43. package/src/features/planning/validate.ts +388 -0
  44. package/src/foundation/action.ts +188 -0
  45. package/src/foundation/change.ts +147 -0
  46. package/src/foundation/instruction.ts +110 -0
  47. package/src/foundation/migration.ts +236 -0
  48. package/src/foundation/plan.ts +245 -0
  49. package/src/foundation/rule.ts +74 -0
  50. package/src/foundation/shortcut.ts +79 -0
  51. package/src/foundation/template.ts +28 -0
  52. package/src/foundation/version.ts +78 -0
  53. package/src/index.ts +22 -11
  54. package/src/renderers/html.ts +12 -0
  55. package/src/renderers/markdown.ts +12 -0
  56. package/src/renderers/mdast.ts +120 -0
  57. package/src/types.ts +2 -0
@@ -0,0 +1,826 @@
1
+ import {
2
+ Cause,
3
+ Context,
4
+ Data,
5
+ Deferred,
6
+ Duration,
7
+ Effect,
8
+ Equal,
9
+ Exit,
10
+ Layer,
11
+ Option,
12
+ } from "effect";
13
+
14
+ import type * as Action from "../../foundation/action.ts";
15
+ import type * as Plan from "../../foundation/plan.ts";
16
+ import type { Node, Occurrence } from "../../foundation/plan.ts";
17
+ import * as Handler from "./handler.ts";
18
+ import { SettlementReference } from "./settlement.ts";
19
+
20
+ /**
21
+ * What happened to one occurrence, or what a dry run predicts.
22
+ *
23
+ * @since @next
24
+ */
25
+ export type Outcome<E = unknown> =
26
+ | { readonly _tag: "Completed" }
27
+ | { readonly _tag: "Skipped"; readonly reason: string }
28
+ | {
29
+ readonly _tag: "Failed";
30
+ readonly phase: Handler.Phase;
31
+ /** The typed failure, when the cause has one. Defects only appear in `cause`. */
32
+ readonly error: E | undefined;
33
+ readonly cause: Cause.Cause<E>;
34
+ }
35
+ | {
36
+ readonly _tag: "Interrupted";
37
+ readonly phase: Handler.Phase;
38
+ /** `handler`: an Effect handler interrupted itself. */
39
+ readonly reason: InterruptReason;
40
+ /**
41
+ * Whether the interrupted work is known to have stopped. An interrupted Promise
42
+ * that has not settled within the grace period may still be changing external
43
+ * state.
44
+ */
45
+ readonly settled: boolean;
46
+ }
47
+ /** Not started because execution stopped first. */
48
+ | { readonly _tag: "Unattempted" }
49
+ | { readonly _tag: "WouldExecute"; readonly evaluated: boolean }
50
+ | { readonly _tag: "WouldSkip"; readonly reason: string }
51
+ | { readonly _tag: "Undetermined"; readonly reason: string }
52
+ | {
53
+ readonly _tag: "PreconditionFailed";
54
+ readonly error: E | undefined;
55
+ readonly cause: Cause.Cause<E>;
56
+ };
57
+
58
+ /** @since @next */
59
+ export type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {
60
+ readonly occurrence: Occurrence<A>;
61
+ readonly outcome: Outcome<E>;
62
+ };
63
+
64
+ /** @since @next */
65
+ export type Report<A extends Action.Any = Action.Any, E = unknown> = {
66
+ readonly _tag: "Report";
67
+ readonly mode: "execute" | "dry-run";
68
+ readonly status:
69
+ | "completed"
70
+ | "failed"
71
+ | "interrupted"
72
+ | "not-started"
73
+ | "would-complete"
74
+ | "would-fail";
75
+ readonly from: string;
76
+ readonly to: string;
77
+ readonly route: string;
78
+ /** Every occurrence in plan order. */
79
+ readonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;
80
+ /** Whether any action body started. A started body may have partially changed state. */
81
+ readonly bodiesStarted: boolean;
82
+ /** Progress is not persisted. Rerunning the plan repeats completed actions. */
83
+ readonly persistence: "none";
84
+ };
85
+
86
+ /**
87
+ * A handler is missing, duplicated, or bound to a different definition.
88
+ *
89
+ * @since @next
90
+ */
91
+ export type CoverageIssue = {
92
+ readonly _tag: "Missing" | "Duplicate" | "Mismatched";
93
+ readonly occurrenceId: string;
94
+ readonly actionId: string;
95
+ readonly description: string;
96
+ readonly migrationId: string;
97
+ /** The rule that produced the occurrence, for replacements. */
98
+ readonly rule: string | undefined;
99
+ /** The occurrences a replacement stands for, so the missing handler is discoverable. */
100
+ readonly replaces: ReadonlyArray<{
101
+ readonly occurrenceId: string;
102
+ readonly description: string;
103
+ }>;
104
+ };
105
+
106
+ const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
107
+
108
+ /**
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.
113
+ *
114
+ * @since @next
115
+ */
116
+ export class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{
117
+ readonly issues: ReadonlyArray<CoverageIssue>;
118
+ readonly report: Report<A, never>;
119
+ }> {
120
+ override get message() {
121
+ return `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues
122
+ .map(
123
+ (issue) =>
124
+ `${issue._tag.toLowerCase()} handler for "${issue.actionId}" (${issue.description})`,
125
+ )
126
+ .join("; ")}.`;
127
+ }
128
+ }
129
+
130
+ const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
131
+
132
+ /**
133
+ * An occurrence failed. Execution stopped admitting new actions; started ones settled.
134
+ *
135
+ * @since @next
136
+ */
137
+ export class ExecutionFailed<
138
+ A extends Action.Any = Action.Any,
139
+ E = unknown,
140
+ > extends ExecutionFailedBase<{
141
+ readonly failures: ReadonlyArray<OccurrenceReport<A, E>>;
142
+ readonly report: Report<A, E>;
143
+ }> {
144
+ override get message() {
145
+ return `Execution failed at ${this.failures
146
+ .map((failure) => `"${failure.occurrence.id}"`)
147
+ .join(", ")}. Completed actions were not rolled back.`;
148
+ }
149
+ }
150
+
151
+ const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
152
+
153
+ /**
154
+ * Why an execution or an occurrence was interrupted: explicit cancellation, a configured
155
+ * timeout, or an Effect handler that interrupted itself.
156
+ *
157
+ * @since @next
158
+ */
159
+ export type InterruptReason = "cancelled" | "timeout" | "handler";
160
+
161
+ const interruptedBy: Record<InterruptReason, string> = {
162
+ cancelled: "cancelled",
163
+ timeout: "stopped by a timeout",
164
+ handler: "interrupted by a handler",
165
+ };
166
+
167
+ /**
168
+ * Explicit cancellation, a configured timeout, or a handler's own interruption stopped
169
+ * execution.
170
+ *
171
+ * @since @next
172
+ */
173
+ export class ExecutionInterrupted<
174
+ A extends Action.Any = Action.Any,
175
+ E = unknown,
176
+ > extends ExecutionInterruptedBase<{
177
+ readonly reason: InterruptReason;
178
+ readonly report: Report<A, E>;
179
+ }> {
180
+ override get message() {
181
+ const pending = this.report.occurrences.filter(
182
+ (entry) => entry.outcome._tag === "Interrupted" && !entry.outcome.settled,
183
+ );
184
+ const suffix =
185
+ pending.length === 0
186
+ ? ""
187
+ : ` ${pending.length} interrupted action(s) had not settled and may still be running.`;
188
+
189
+ return `Execution was ${interruptedBy[this.reason]}.${suffix}`;
190
+ }
191
+ }
192
+
193
+ /** @since @next */
194
+ export type ExecutionError<A extends Action.Any, E> =
195
+ | HandlerCoverageError<A>
196
+ | ExecutionFailed<A, E>
197
+ | ExecutionInterrupted<A, E>;
198
+
199
+ /**
200
+ * Action identifiers of a statically covered plan that no handler in the array
201
+ * implements.
202
+ *
203
+ * @since @next
204
+ */
205
+ export type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = "runtime" extends C
206
+ ? never
207
+ : A extends Action.Any
208
+ ? string extends A["id"]
209
+ ? never
210
+ : A["id"] extends Handler.ActionId<H>
211
+ ? never
212
+ : A["id"]
213
+ : never;
214
+
215
+ /** Rejects a handler array that leaves statically known actions uncovered, naming them. */
216
+ type CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [
217
+ Uncovered<A, H, C>,
218
+ ] extends [never]
219
+ ? unknown
220
+ : { readonly handlers: `Missing a handler for action "${Uncovered<A, H, C>}"` };
221
+
222
+ /**
223
+ * Errors an execution can report for its occurrences.
224
+ *
225
+ * @since @next
226
+ */
227
+ export type Errors<H> = Handler.Error<H>;
228
+
229
+ /**
230
+ * Effect services an execution requires: the services of its handlers.
231
+ *
232
+ * @since @next
233
+ */
234
+ export type Requirements<H> = Handler.Services<H>;
235
+
236
+ /** @since @next */
237
+ export type Options<H extends Handler.Any> = {
238
+ readonly handlers?: ReadonlyArray<H>;
239
+ /**
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.
243
+ */
244
+ readonly dryRun?: boolean;
245
+ /**
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.
248
+ */
249
+ readonly timeout?: Duration.Input;
250
+ /**
251
+ * How long to wait for an interrupted Promise callback to settle before reporting it
252
+ * as possibly still running. Defaults to 5 seconds.
253
+ */
254
+ readonly settleTimeout?: Duration.Input;
255
+ };
256
+
257
+ /** A handler as the executor runs it: its action is erased, its channels are not. */
258
+ type Internal<E, R> = Handler.Handler<Action.Any, E, R>;
259
+
260
+ type Resolved<E, R> = Map<string, Internal<E, R>>;
261
+
262
+ const describeReplaces = (occurrence: Occurrence) =>
263
+ occurrence.origin._tag === "Replacement"
264
+ ? occurrence.origin.replaces.map((replaced) => ({
265
+ occurrenceId: replaced.id,
266
+ description: replaced.action.description,
267
+ }))
268
+ : [];
269
+
270
+ const coverage = <E, R>(
271
+ plan: Plan.Any,
272
+ handlers: ReadonlyArray<Internal<E, R>>,
273
+ ): { readonly resolved: Resolved<E, R>; readonly issues: ReadonlyArray<CoverageIssue> } => {
274
+ const byAction = new Map<string, Array<Internal<E, R>>>();
275
+ for (const handler of handlers) {
276
+ const list = byAction.get(handler.action.id) ?? [];
277
+ list.push(handler);
278
+ byAction.set(handler.action.id, list);
279
+ }
280
+
281
+ const resolved: Resolved<E, R> = new Map();
282
+ const issues: Array<CoverageIssue> = [];
283
+ for (const occurrence of plan.occurrences) {
284
+ const issue = (tag: CoverageIssue["_tag"]) =>
285
+ issues.push({
286
+ _tag: tag,
287
+ occurrenceId: occurrence.id,
288
+ actionId: occurrence.action.id,
289
+ description: occurrence.action.description,
290
+ migrationId: occurrence.migration.id,
291
+ rule:
292
+ occurrence.origin._tag === "Replacement"
293
+ ? occurrence.origin.rule.id
294
+ : undefined,
295
+ replaces: describeReplaces(occurrence),
296
+ });
297
+
298
+ const candidates = byAction.get(occurrence.action.id) ?? [];
299
+ const [selected] = candidates;
300
+ if (candidates.length > 1) issue("Duplicate");
301
+ else if (selected === undefined) issue("Missing");
302
+ else if (
303
+ selected.action.kind !== occurrence.action.kind ||
304
+ !Equal.equals(selected.action.payload, occurrence.action.payload)
305
+ ) {
306
+ issue("Mismatched");
307
+ } else resolved.set(occurrence.id, selected);
308
+ }
309
+
310
+ return { resolved, issues };
311
+ };
312
+
313
+ const report = <A extends Action.Any, E>(
314
+ plan: Plan.Plan<A, Plan.Coverage>,
315
+ mode: Report["mode"],
316
+ status: Report["status"],
317
+ outcomes: ReadonlyMap<string, Outcome<E>>,
318
+ bodiesStarted: boolean,
319
+ ): Report<A, E> => ({
320
+ _tag: "Report",
321
+ mode,
322
+ status,
323
+ from: plan.from.id,
324
+ to: plan.to.id,
325
+ route: plan.route.id,
326
+ occurrences: plan.occurrences.map((occurrence) => ({
327
+ occurrence,
328
+ outcome: outcomes.get(occurrence.id) ?? { _tag: "Unattempted" },
329
+ })),
330
+ bodiesStarted,
331
+ persistence: "none",
332
+ });
333
+
334
+ const failureOf = <E>(cause: Cause.Cause<E>) => ({
335
+ error: Option.getOrUndefined(Cause.findErrorOption(cause)),
336
+ cause,
337
+ });
338
+
339
+ const forEachBranch = <R>(
340
+ branches: ReadonlyArray<Node>,
341
+ concurrency: Action.Concurrency,
342
+ run: (node: Node) => Effect.Effect<void, never, R>,
343
+ ) => Effect.forEach(branches, run, { concurrency, discard: true });
344
+
345
+ /** Registers a callback that cancels the execution. Only `runPromise` uses it. */
346
+ type Subscribe = (cancel: () => void) => void;
347
+
348
+ type StopReason = "failure" | InterruptReason;
349
+
350
+ type PhaseResult<T, E> =
351
+ | { readonly _tag: "Done"; readonly exit: Exit.Exit<T, E> }
352
+ | {
353
+ readonly _tag: "Interrupted";
354
+ readonly reason: "cancelled" | "timeout";
355
+ readonly settled: boolean;
356
+ };
357
+
358
+ type ControlOptions = Pick<Options<never>, "timeout" | "settleTimeout">;
359
+
360
+ /** Admission state, cancellation, and timeouts shared by real and dry runs. */
361
+ const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>
362
+ Effect.gen(function* () {
363
+ const halt: { reason: StopReason | undefined } = { reason: undefined };
364
+ const cancelled = yield* Deferred.make<"cancelled">();
365
+ const settleTimeout = options.settleTimeout ?? Duration.seconds(5);
366
+
367
+ const stop = (reason: StopReason) => {
368
+ halt.reason ??= reason;
369
+ };
370
+ subscribe?.(() => {
371
+ stop("cancelled");
372
+ Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
373
+ });
374
+
375
+ /** Runs one precondition or body, racing it against cancellation and the timeout. */
376
+ const runPhase = <T, E, R>(
377
+ work: Effect.Effect<T, E, R>,
378
+ ): Effect.Effect<PhaseResult<T, E>, never, R> =>
379
+ Effect.gen(function* () {
380
+ let settled = true;
381
+ const tracked = work.pipe(
382
+ Effect.provideService(SettlementReference, {
383
+ grace: settleTimeout,
384
+ record: (value) => {
385
+ settled = value;
386
+ },
387
+ }),
388
+ );
389
+ const stopSignals: Array<Effect.Effect<"cancelled" | "timeout">> = [
390
+ Deferred.await(cancelled),
391
+ ];
392
+ if (options.timeout !== undefined) {
393
+ stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout" as const));
394
+ }
395
+ const result = yield* Effect.raceFirst(
396
+ Effect.map(Effect.exit(tracked), (exit) => ({ _tag: "Done" as const, exit })),
397
+ Effect.raceAll(stopSignals).pipe(
398
+ // Stop admission as soon as the signal fires. The race returns only after
399
+ // the interrupted work has had its settlement grace period.
400
+ Effect.tap((reason) => Effect.sync(() => stop(reason))),
401
+ Effect.map((reason) => ({ _tag: "Stop" as const, reason })),
402
+ ),
403
+ );
404
+ if (result._tag === "Done") return result;
405
+
406
+ // A timeout interrupts only this action. Siblings settle as after any failure.
407
+ return { _tag: "Interrupted" as const, reason: result.reason, settled };
408
+ });
409
+
410
+ return { halt, stop, runPhase };
411
+ });
412
+
413
+ const interrupted = <A extends Action.Any, E>(
414
+ plan: Plan.Plan<A, Plan.Coverage>,
415
+ mode: Report["mode"],
416
+ reason: InterruptReason,
417
+ outcomes: ReadonlyMap<string, Outcome<E>>,
418
+ bodiesStarted: boolean,
419
+ ) =>
420
+ new ExecutionInterrupted({
421
+ reason,
422
+ report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
423
+ });
424
+
425
+ const execute = <A extends Action.Any, E, R>(
426
+ plan: Plan.Plan<A, Plan.Coverage>,
427
+ resolved: Resolved<E, R>,
428
+ options: ControlOptions,
429
+ subscribe: Subscribe | undefined,
430
+ ): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
431
+ Effect.gen(function* () {
432
+ const outcomes = new Map<string, Outcome<E>>();
433
+ const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
434
+ let bodiesStarted = false;
435
+
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;
454
+ }
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,
465
+ });
466
+
467
+ return;
468
+ }
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
+
477
+ return;
478
+ }
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
+ stop("failure");
517
+ outcomes.set(occurrence.id, {
518
+ _tag: "Failed",
519
+ phase: "body",
520
+ ...failureOf(ran.exit.cause),
521
+ });
522
+
523
+ return;
524
+ }
525
+ outcomes.set(occurrence.id, { _tag: "Completed" });
526
+ });
527
+
528
+ const runNode = (node: Node): Effect.Effect<void, never, R> => {
529
+ switch (node._tag) {
530
+ case "Occurrence":
531
+ return runOccurrence(node);
532
+ case "Sequence":
533
+ return Effect.forEach(node.children, runNode, { discard: true });
534
+ }
535
+
536
+ // Sibling failures stop admission through `halt`; they never interrupt branches.
537
+ return forEachBranch(node.branches, node.concurrency, runNode);
538
+ };
539
+
540
+ for (const step of plan.steps) {
541
+ // Migration steps are barriers: a step starts only after the previous one settled.
542
+ if (halt.reason !== undefined) break;
543
+ yield* runNode(step.node);
544
+ }
545
+
546
+ if (halt.reason === undefined)
547
+ return report(plan, "execute", "completed", outcomes, bodiesStarted);
548
+ if (halt.reason === "failure") {
549
+ const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
550
+
551
+ return yield* new ExecutionFailed({
552
+ failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
553
+ report: result,
554
+ });
555
+ }
556
+
557
+ return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
558
+ });
559
+
560
+ const dryRun = <A extends Action.Any, E, R>(
561
+ plan: Plan.Plan<A, Plan.Coverage>,
562
+ resolved: Resolved<E, R>,
563
+ options: ControlOptions,
564
+ subscribe: Subscribe | undefined,
565
+ ): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
566
+ Effect.gen(function* () {
567
+ const outcomes = new Map<string, Outcome<E>>();
568
+ const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
569
+ let failedAt: string | undefined;
570
+
571
+ /** Returns whether the node would or might change state. */
572
+ const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
573
+ Effect.gen(function* () {
574
+ if (node._tag === "Sequence") {
575
+ let current = dirty;
576
+ for (const child of node.children) current = yield* visit(child, current);
577
+
578
+ return current;
579
+ }
580
+ if (node._tag === "Parallel") {
581
+ // Branches are independent: each starts from the state before the group.
582
+ // They are evaluated one at a time so the report is deterministic.
583
+ let changed = dirty;
584
+ for (const branch of node.branches)
585
+ changed = (yield* visit(branch, dirty)) || changed;
586
+
587
+ return changed;
588
+ }
589
+
590
+ const handler = resolved.get(node.id);
591
+ if (handler === undefined || halt.reason !== undefined) return dirty;
592
+ if (failedAt !== undefined) {
593
+ outcomes.set(node.id, {
594
+ _tag: "Undetermined",
595
+ reason: `Execution would stop at the failed precondition of "${failedAt}".`,
596
+ });
597
+
598
+ return true;
599
+ }
600
+ if (handler.precondition === undefined) {
601
+ outcomes.set(node.id, { _tag: "WouldExecute", evaluated: false });
602
+
603
+ return true;
604
+ }
605
+ if (dirty) {
606
+ outcomes.set(node.id, {
607
+ _tag: "Undetermined",
608
+ reason: "The precondition depends on earlier actions that a dry run does not apply.",
609
+ });
610
+
611
+ return true;
612
+ }
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;
638
+ outcomes.set(node.id, {
639
+ _tag: "PreconditionFailed",
640
+ ...failureOf(checked.exit.cause),
641
+ });
642
+
643
+ return true;
644
+ }
645
+ if (!checked.exit.value) {
646
+ outcomes.set(node.id, { _tag: "WouldSkip", reason: handler.skipReason });
647
+
648
+ return false;
649
+ }
650
+ outcomes.set(node.id, { _tag: "WouldExecute", evaluated: true });
651
+
652
+ return true;
653
+ });
654
+
655
+ // Later migrations conservatively depend on every earlier migration.
656
+ let dirty = false;
657
+ for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
658
+
659
+ if (halt.reason !== undefined && halt.reason !== "failure") {
660
+ return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
661
+ }
662
+
663
+ return report(
664
+ plan,
665
+ "dry-run",
666
+ failedAt === undefined ? "would-complete" : "would-fail",
667
+ outcomes,
668
+ false,
669
+ );
670
+ });
671
+
672
+ const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.Any>(
673
+ plan: Plan.Plan<A, C>,
674
+ options: Options<H>,
675
+ 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 ?? [];
681
+
682
+ return Effect.gen(function* () {
683
+ const checked = coverage(plan, handlers);
684
+ if (checked.issues.length > 0) {
685
+ return yield* new HandlerCoverageError({
686
+ issues: checked.issues,
687
+ report: report(
688
+ plan,
689
+ options.dryRun === true ? "dry-run" : "execute",
690
+ "not-started",
691
+ new Map<string, Outcome<never>>(),
692
+ false,
693
+ ),
694
+ });
695
+ }
696
+
697
+ return options.dryRun === true
698
+ ? yield* dryRun(plan, checked.resolved, options, subscribe)
699
+ : yield* execute(plan, checked.resolved, options, subscribe);
700
+ });
701
+ };
702
+
703
+ /**
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.
708
+ *
709
+ * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
710
+ * signal passed to Promise callbacks. The effect then ends as interrupted, without a
711
+ * report.
712
+ *
713
+ * @since @next
714
+ */
715
+ export const effect = <
716
+ A extends Action.Any,
717
+ C extends Plan.Coverage,
718
+ H extends Handler.Any = never,
719
+ >(
720
+ 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);
724
+
725
+ type ServicesOption<R, LE> = [R] extends [never]
726
+ ? {
727
+ /** Handlers without Effect services need none. */
728
+ readonly services?: Context.Context<never> | Layer.Layer<never, LE>;
729
+ }
730
+ : {
731
+ /** Supplies the handlers' Effect services. */
732
+ readonly services: Context.Context<R> | Layer.Layer<R, LE>;
733
+ };
734
+
735
+ /** @since @next */
736
+ export type PromiseOptions<H extends Handler.Any> = Options<H> & {
737
+ /**
738
+ * Explicit cancellation. Aborting stops admission, interrupts running actions, and
739
+ * rejects with `ExecutionInterrupted` and the partial report.
740
+ */
741
+ readonly signal?: AbortSignal;
742
+ };
743
+
744
+ /**
745
+ * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
746
+ * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
747
+ * Building a supplied services layer can also reject with the layer's own error,
748
+ * without a report.
749
+ *
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.
754
+ *
755
+ * @since @next
756
+ */
757
+ export const runPromise = <
758
+ A extends Action.Any,
759
+ C extends Plan.Coverage,
760
+ H extends Handler.Any = never,
761
+ LE = never,
762
+ >(
763
+ plan: Plan.Plan<A, C>,
764
+ options: PromiseOptions<H> & ServicesOption<Requirements<H>, LE> & CoverageCheck<A, H, C>,
765
+ ): Promise<Report<A, Errors<H>>> => {
766
+ const { signal } = options;
767
+ const notStarted = () =>
768
+ new ExecutionInterrupted({
769
+ reason: "cancelled",
770
+ report: report(
771
+ plan,
772
+ options.dryRun === true ? "dry-run" : "execute",
773
+ "interrupted",
774
+ new Map<string, Outcome<Errors<H>>>(),
775
+ false,
776
+ ),
777
+ });
778
+ if (signal?.aborted === true) return Promise.reject(notStarted());
779
+
780
+ // Until the run installs its own cancellation, an abort stops building the services
781
+ // layer. Afterwards the run stops admission and reports partial progress.
782
+ const abortedBeforeRun = Deferred.makeUnsafe<void>();
783
+ let cancelRun: (() => void) | undefined;
784
+ const onAbort = () => {
785
+ if (cancelRun === undefined) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);
786
+ else cancelRun();
787
+ };
788
+ signal?.addEventListener("abort", onAbort, { once: true });
789
+ const subscribe: Subscribe | undefined =
790
+ signal === undefined
791
+ ? undefined
792
+ : (cancel) => {
793
+ cancelRun = cancel;
794
+ if (signal.aborted) cancel();
795
+ };
796
+ const program = run(plan, options, subscribe);
797
+ const services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;
798
+ const provided =
799
+ services === undefined
800
+ ? program
801
+ : Context.isContext(services)
802
+ ? 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);
806
+ const cancellable =
807
+ signal === undefined
808
+ ? provided
809
+ : Effect.raceFirst(
810
+ provided,
811
+ Effect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())),
812
+ );
813
+
814
+ return Effect.runPromiseExit(
815
+ // `ServicesOption` requires services that cover every requirement. A layer that
816
+ // fails to build rejects with its own error.
817
+ // 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>,
819
+ )
820
+ .finally(() => signal?.removeEventListener("abort", onAbort))
821
+ .then((exit) => {
822
+ if (Exit.isSuccess(exit)) return exit.value;
823
+
824
+ throw Cause.squash(exit.cause);
825
+ });
826
+ };