deltafold 0.1.0 → 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.
package/dist/index.js CHANGED
@@ -172,16 +172,48 @@ const trackPromise = (start) => Effect.suspend(() => {
172
172
  if (Option.isNone(settled)) settlement.unsettled(settles);
173
173
  })));
174
174
  });
175
+ // src/features/execution/promise-callback.ts
176
+ const declaredError = (guards) => (cause) => guards.some((guard) => Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause));
177
+ /**
178
+ * Turns Promise callbacks into Effects. Declared services are resolved before each
179
+ * call, rejections that a guard recognizes keep their type, and `unexpected` wraps the
180
+ * rest.
181
+ */
182
+ const adaptPromise = (options) => {
183
+ const isDeclared = declaredError(options.errors ?? []);
184
+ const services = options.services ?? {};
185
+ const resolve = Effect.map(Effect.context(), (context) => Object.fromEntries(Reflect.ownKeys(services).map((name) => [name, Context.get(context, services[name])])));
186
+ return (callback, unexpected) => Effect.flatMap(resolve, (resolved) => trackPromise((capture) => Effect.tryPromise({
187
+ try: (signal) => capture(Promise.resolve(callback({
188
+ signal,
189
+ services: resolved
190
+ }))),
191
+ catch: (cause) => isDeclared(cause) ? cause : unexpected(cause)
192
+ })));
193
+ };
175
194
  // src/features/execution/handler.ts
176
195
  var handler_exports = /* @__PURE__ */ __exportAll({
177
196
  UnexpectedHandlerError: () => UnexpectedHandlerError,
178
- effect: () => effect$1,
197
+ VerificationFailed: () => VerificationFailed,
198
+ effect: () => effect$2,
179
199
  isHandler: () => isHandler,
200
+ manual: () => manual,
201
+ manualEffect: () => manualEffect,
180
202
  prepared: () => prepared,
181
- promise: () => promise,
203
+ promise: () => promise$1,
182
204
  skip: () => skip
183
205
  });
184
206
  /**
207
+ * A person confirmed manual work, and the handler's `verify` check returned `false`.
208
+ *
209
+ * @since @next
210
+ */
211
+ var VerificationFailed = class extends Data.TaggedError("VerificationFailed") {
212
+ get message() {
213
+ return `Manual work for action "${this.actionId}" was confirmed, but its verification check did not pass`;
214
+ }
215
+ };
216
+ /**
185
217
  * A Promise handler rejected or threw a value that none of its declared error guards
186
218
  * recognized, or its prepare phase returned something other than `Handler.prepared` or
187
219
  * `Handler.skip`.
@@ -217,33 +249,25 @@ const applyStep = (apply) => ({
217
249
  _tag: "Apply",
218
250
  apply
219
251
  });
220
- const TypeId = "~deltafold/Handler";
252
+ const TypeId$1 = "~deltafold/Handler";
221
253
  /** @since @next */
222
- const isHandler = (value) => Predicate.hasProperty(value, TypeId);
254
+ const isHandler = (value) => Predicate.hasProperty(value, TypeId$1);
223
255
  const make$5 = (action, prepares, prepare) => ({
224
- [TypeId]: TypeId,
256
+ [TypeId$1]: TypeId$1,
225
257
  action,
258
+ performer: "automated",
226
259
  prepares,
227
260
  prepare
228
261
  });
229
- const declaredError = (guards) => (cause) => guards.some((guard) => Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause));
230
- function promise(action, run, options) {
231
- const isDeclared = declaredError(options?.errors ?? []);
232
- const services = options?.services ?? {};
233
- const resolve = Effect.map(Effect.context(), (context) => Object.fromEntries(Reflect.ownKeys(services).map((name) => [name, Context.get(context, services[name])])));
262
+ function promise$1(action, run, options) {
263
+ const adaptCallback = adaptPromise(options ?? {});
234
264
  const unexpected = (phase, cause) => new UnexpectedHandlerError({
235
265
  actionId: action.id,
236
266
  kind: action.kind,
237
267
  phase,
238
268
  cause
239
269
  });
240
- const adapt = (phase, callback) => Effect.flatMap(resolve, (resolved) => trackPromise((capture) => Effect.tryPromise({
241
- try: (signal) => capture(Promise.resolve(callback({
242
- signal,
243
- services: resolved
244
- }))),
245
- catch: (cause) => isDeclared(cause) ? cause : unexpected(phase, cause)
246
- })));
270
+ const adapt = (phase, callback) => adaptCallback(callback, (cause) => unexpected(phase, cause));
247
271
  if (Predicate.isFunction(run)) {
248
272
  const apply = Effect.asVoid(adapt("apply", (context) => run(action.payload, context)));
249
273
  return make$5(action, false, () => Effect.succeed(applyStep(apply)));
@@ -254,19 +278,51 @@ function promise(action, run, options) {
254
278
  }))))));
255
279
  return make$5(action, true, () => prepare);
256
280
  }
257
- function effect$1(action, run) {
281
+ function effect$2(action, run) {
258
282
  if (Predicate.isFunction(run)) {
259
283
  const apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));
260
284
  return make$5(action, false, (scope) => Effect.succeed(applyStep(Scope.provide(apply, scope))));
261
285
  }
262
286
  return make$5(action, true, (scope) => Effect.suspend(() => run.prepare(action.payload)).pipe(Scope.provide(scope), Effect.filterOrElse(isPreparation, () => Effect.die(notAPreparation())), Effect.map((preparation) => preparation._tag === "Skip" ? preparation : applyStep(Scope.provide(Effect.asVoid(Effect.suspend(() => run.apply(preparation.value, { payload: action.payload }))), scope)))));
263
287
  }
288
+ const verified = (action, check) => Effect.flatMap(check, (passed) => passed ? Effect.void : Effect.fail(new VerificationFailed({
289
+ actionId: action.id,
290
+ kind: action.kind
291
+ })));
292
+ const makeManual = (action, verify) => ({
293
+ [TypeId$1]: TypeId$1,
294
+ action,
295
+ performer: "manual",
296
+ prepares: false,
297
+ prepare: (scope) => Effect.succeed({
298
+ _tag: "Confirm",
299
+ verify: verify?.(scope)
300
+ })
301
+ });
302
+ function manual(action, options) {
303
+ const adapt = adaptPromise(options ?? {});
304
+ const verify = options?.verify;
305
+ if (verify === void 0) return makeManual(action, void 0);
306
+ const check = verified(action, adapt((context) => verify(action.payload, context), (cause) => new UnexpectedHandlerError({
307
+ actionId: action.id,
308
+ kind: action.kind,
309
+ phase: "verification",
310
+ cause
311
+ })));
312
+ return makeManual(action, () => check);
313
+ }
314
+ function manualEffect(action, options) {
315
+ const verify = options?.verify;
316
+ if (verify === void 0) return makeManual(action, void 0);
317
+ return makeManual(action, (scope) => Scope.provide(verified(action, Effect.suspend(() => verify(action.payload))), scope));
318
+ }
264
319
  // src/features/execution/executor.ts
265
320
  var executor_exports = /* @__PURE__ */ __exportAll({
266
321
  ExecutionFailed: () => ExecutionFailed,
267
322
  ExecutionInterrupted: () => ExecutionInterrupted,
268
323
  HandlerCoverageError: () => HandlerCoverageError,
269
- effect: () => effect,
324
+ InteractionUnavailable: () => InteractionUnavailable,
325
+ effect: () => effect$1,
270
326
  runPromise: () => runPromise
271
327
  });
272
328
  const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
@@ -283,15 +339,29 @@ var HandlerCoverageError = class extends HandlerCoverageBase {
283
339
  return `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues.map((issue) => `${issue._tag.toLowerCase()} handler for "${issue.actionId}" (${issue.description})`).join("; ")}.`;
284
340
  }
285
341
  };
342
+ const InteractionUnavailableBase = Data.TaggedError("InteractionUnavailable");
343
+ /**
344
+ * The plan has manual handlers, and the run has no `interaction` to ask a person. The
345
+ * run fails before any handler phase or prompt.
346
+ *
347
+ * @since @next
348
+ */
349
+ var InteractionUnavailable = class extends InteractionUnavailableBase {
350
+ get message() {
351
+ return `No interaction is available to confirm manual work for ${this.occurrences.map((occurrence) => `"${occurrence.id}" (${occurrence.action.description})`).join(", ")}. Supply the \`interaction\` option, or bind automated handlers to these actions.`;
352
+ }
353
+ };
354
+ const listIds = (entries) => entries.map((entry) => entry.outcome._tag === "Failed" ? `"${entry.occurrence.id}" (${entry.outcome.phase})` : `"${entry.occurrence.id}"`).join(", ");
286
355
  const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
287
356
  /**
288
- * An occurrence failed. Execution stopped admitting new actions; started ones settled.
357
+ * An occurrence failed, or a person declined manual work. Execution stopped admitting
358
+ * new actions; started ones settled.
289
359
  *
290
360
  * @since @next
291
361
  */
292
362
  var ExecutionFailed = class extends ExecutionFailedBase {
293
363
  get message() {
294
- return `Execution failed at ${this.failures.map((failure) => `"${failure.occurrence.id}"`).join(", ")}. Completed actions were not rolled back.`;
364
+ return `${[...this.failures.length === 0 ? [] : [`Execution failed at ${listIds(this.failures)}.`], ...this.declined.length === 0 ? [] : [`Manual work was declined at ${listIds(this.declined)}, which stopped the run.`]].join(" ")} Completed actions were not rolled back.`;
295
365
  }
296
366
  };
297
367
  const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
@@ -392,7 +462,9 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
392
462
  const stop = (reason) => {
393
463
  halt.reason ??= reason;
394
464
  };
465
+ let cancellationArrived = false;
395
466
  subscribe?.(() => {
467
+ cancellationArrived = true;
396
468
  stop("cancelled");
397
469
  Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
398
470
  });
@@ -400,7 +472,7 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
400
472
  * Runs one phase, racing it against cancellation and its own timeout. An
401
473
  * interrupted Promise that outlives the settlement grace period goes to `unsettled`.
402
474
  */
403
- const runPhase = (work, unsettled) => Effect.gen(function* () {
475
+ const runPhase = (work, unsettled, timing = "timed") => Effect.gen(function* () {
404
476
  let settled = true;
405
477
  const tracked = work.pipe(Effect.provideService(SettlementReference, {
406
478
  grace: settleTimeout,
@@ -410,7 +482,7 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
410
482
  }
411
483
  }));
412
484
  const stopSignals = [Deferred.await(cancelled)];
413
- if (options.timeout !== void 0) stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout"));
485
+ if (options.timeout !== void 0 && timing === "timed") stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout"));
414
486
  const result = yield* Effect.raceFirst(Effect.map(Effect.exit(tracked), (exit) => ({
415
487
  _tag: "Done",
416
488
  exit
@@ -428,7 +500,8 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
428
500
  return {
429
501
  halt,
430
502
  stop,
431
- runPhase
503
+ runPhase,
504
+ isCancelled: () => cancellationArrived
432
505
  };
433
506
  });
434
507
  /**
@@ -475,9 +548,9 @@ const unsuccessful = (phase, result, stop) => {
475
548
  };
476
549
  }
477
550
  };
478
- const execute = (plan, resolved, options, subscribe, retain) => Effect.gen(function* () {
551
+ const execute = (plan, resolved, interaction, options, subscribe, retain) => Effect.gen(function* () {
479
552
  const outcomes = /* @__PURE__ */ new Map();
480
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
553
+ const { halt, stop, runPhase, isCancelled } = yield* makeControl(options, subscribe);
481
554
  let bodiesStarted = false;
482
555
  const runOccurrence = (occurrence) => {
483
556
  if (halt.reason !== void 0) return Effect.void;
@@ -515,6 +588,42 @@ const execute = (plan, resolved, options, subscribe, retain) => Effect.gen(funct
515
588
  _tag: "Skipped",
516
589
  reason: step.reason
517
590
  });
591
+ if (step._tag === "Confirm") {
592
+ if (interaction === void 0) return Exit.void;
593
+ phase = "confirmation";
594
+ bodiesStarted = true;
595
+ const asked = yield* runPhase(interaction.confirm({ occurrence }), unsettled, "untimed");
596
+ const unanswered = unsuccessful("confirmation", asked, stop);
597
+ if (unanswered !== void 0) return end(unanswered);
598
+ if (asked._tag !== "Done") return Exit.void;
599
+ if (Exit.isFailure(asked.exit)) return fail(asked.exit.cause);
600
+ if (asked.exit.value === "declined") {
601
+ stop("failure");
602
+ return end({ _tag: "Declined" });
603
+ }
604
+ if (step.verify === void 0) return end({
605
+ _tag: "Completed",
606
+ performer: "manual",
607
+ confirmation: "asserted"
608
+ });
609
+ phase = "verification";
610
+ if (isCancelled()) return end({
611
+ _tag: "Interrupted",
612
+ phase,
613
+ reason: "cancelled",
614
+ settled: true
615
+ });
616
+ const checked = yield* runPhase(step.verify, unsettled);
617
+ const unchecked = unsuccessful("verification", checked, stop);
618
+ if (unchecked !== void 0) return end(unchecked);
619
+ if (checked._tag !== "Done") return Exit.void;
620
+ if (Exit.isFailure(checked.exit)) return fail(checked.exit.cause);
621
+ return end({
622
+ _tag: "Completed",
623
+ performer: "manual",
624
+ confirmation: "verified"
625
+ });
626
+ }
518
627
  phase = "apply";
519
628
  bodiesStarted = true;
520
629
  const applied = yield* runPhase(step.apply, unsettled);
@@ -522,7 +631,10 @@ const execute = (plan, resolved, options, subscribe, retain) => Effect.gen(funct
522
631
  if (stopped !== void 0) return end(stopped);
523
632
  if (applied._tag !== "Done") return Exit.void;
524
633
  if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
525
- return end({ _tag: "Completed" });
634
+ return end({
635
+ _tag: "Completed",
636
+ performer: "automated"
637
+ });
526
638
  });
527
639
  const onCleanupFailure = (cause) => Effect.suspend(() => {
528
640
  const outcome = outcomes.get(occurrence.id);
@@ -553,6 +665,7 @@ const execute = (plan, resolved, options, subscribe, retain) => Effect.gen(funct
553
665
  const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
554
666
  return yield* new ExecutionFailed({
555
667
  failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
668
+ declined: result.occurrences.filter((entry) => entry.outcome._tag === "Declined"),
556
669
  report: result
557
670
  });
558
671
  }
@@ -586,7 +699,8 @@ const dryRun = (plan, resolved, options, subscribe, retain) => Effect.gen(functi
586
699
  reason: step.reason
587
700
  } : {
588
701
  _tag: "WouldExecute",
589
- evaluated: true
702
+ evaluated: true,
703
+ performer: handler.performer
590
704
  });
591
705
  });
592
706
  const onCleanupFailure = (cause) => Effect.suspend(() => {
@@ -618,21 +732,24 @@ const dryRun = (plan, resolved, options, subscribe, retain) => Effect.gen(functi
618
732
  if (failedAt !== void 0) {
619
733
  outcomes.set(node.id, {
620
734
  _tag: "Undetermined",
621
- reason: `Execution would stop at the failed preparation of "${failedAt}".`
735
+ reason: `Execution would stop at the failed preparation of "${failedAt}".`,
736
+ performer: handler.performer
622
737
  });
623
738
  return true;
624
739
  }
625
740
  if (!handler.prepares) {
626
741
  outcomes.set(node.id, {
627
742
  _tag: "WouldExecute",
628
- evaluated: false
743
+ evaluated: false,
744
+ performer: handler.performer
629
745
  });
630
746
  return true;
631
747
  }
632
748
  if (dirty) {
633
749
  outcomes.set(node.id, {
634
750
  _tag: "Undetermined",
635
- reason: "The prepare phase depends on earlier actions that a dry run does not apply."
751
+ reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
752
+ performer: handler.performer
636
753
  });
637
754
  return true;
638
755
  }
@@ -646,17 +763,25 @@ const dryRun = (plan, resolved, options, subscribe, retain) => Effect.gen(functi
646
763
  });
647
764
  const run = (plan, options, subscribe, retain) => {
648
765
  const handlers = options.handlers ?? [];
766
+ const interaction = options.interaction;
649
767
  return Effect.gen(function* () {
650
768
  const checked = coverage(plan, handlers);
651
769
  if (checked.issues.length > 0) return yield* new HandlerCoverageError({
652
770
  issues: checked.issues,
653
771
  report: report(plan, options.dryRun === true ? "dry-run" : "execute", "not-started", /* @__PURE__ */ new Map(), false)
654
772
  });
655
- return options.dryRun === true ? yield* dryRun(plan, checked.resolved, options, subscribe, retain) : yield* execute(plan, checked.resolved, options, subscribe, retain);
773
+ if (options.dryRun === true) return yield* dryRun(plan, checked.resolved, options, subscribe, retain);
774
+ const manual = plan.occurrences.filter((occurrence) => checked.resolved.get(occurrence.id)?.performer === "manual");
775
+ if (manual.length > 0 && interaction === void 0) return yield* new InteractionUnavailable({
776
+ occurrences: manual,
777
+ report: report(plan, "execute", "not-started", /* @__PURE__ */ new Map(), false)
778
+ });
779
+ return yield* execute(plan, checked.resolved, interaction, options, subscribe, retain);
656
780
  });
657
781
  };
658
782
  /**
659
- * Runs a plan as an Effect. Coverage is checked before any handler phase runs. Steps
783
+ * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,
784
+ * are checked before any handler phase runs. Steps
660
785
  * are sequential barriers; parallel groups run their branches concurrently. On failure,
661
786
  * no new action starts, and actions already running settle before the effect fails
662
787
  * with the partial report.
@@ -672,10 +797,11 @@ const run = (plan, options, subscribe, retain) => {
672
797
  *
673
798
  * @since @next
674
799
  */
675
- const effect = (plan, options) => run(plan, options, void 0, () => {});
800
+ const effect$1 = (plan, options) => run(plan, options, void 0, () => {});
676
801
  /**
677
802
  * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
678
- * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
803
+ * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying
804
+ * the partial report.
679
805
  * Building a supplied services layer can also reject with the layer's own error,
680
806
  * without a report.
681
807
  *
@@ -727,6 +853,76 @@ const runPromise = (plan, options) => {
727
853
  throw Cause.squash(exit.cause);
728
854
  });
729
855
  };
856
+ // src/features/execution/interaction.ts
857
+ var interaction_exports = /* @__PURE__ */ __exportAll({
858
+ UnexpectedInteractionError: () => UnexpectedInteractionError,
859
+ effect: () => effect,
860
+ isInteraction: () => isInteraction,
861
+ promise: () => promise
862
+ });
863
+ /**
864
+ * A Promise interaction rejected with a value that none of its declared error guards
865
+ * recognized (`rejected`), or an interaction answered with something other than
866
+ * `"confirmed"` or `"declined"` (`invalid-answer`). An invalid answer is never kept: it
867
+ * may be text that the person typed.
868
+ *
869
+ * @since @next
870
+ */
871
+ var UnexpectedInteractionError = class extends Data.TaggedError("UnexpectedInteractionError") {
872
+ get message() {
873
+ return this.reason === "rejected" ? `The interaction failed unexpectedly while confirming "${this.occurrenceId}"` : `The interaction answered neither "confirmed" nor "declined" for "${this.occurrenceId}"`;
874
+ }
875
+ };
876
+ const isAnswer = (value) => value === "confirmed" || value === "declined";
877
+ const checkAnswer = (request) => (answer) => isAnswer(answer) ? Effect.succeed(answer) : Effect.fail(new UnexpectedInteractionError({
878
+ occurrenceId: request.occurrence.id,
879
+ reason: "invalid-answer",
880
+ cause: void 0
881
+ }));
882
+ const TypeId = "~deltafold/Interaction";
883
+ /** @since @next */
884
+ const isInteraction = (value) => Predicate.hasProperty(value, TypeId);
885
+ /**
886
+ * Confirms manual work with a Promise callback. It receives `{ signal, services }`: an
887
+ * `AbortSignal` that aborts when the run is cancelled, so it can stop asking, and the
888
+ * declared services.
889
+ *
890
+ * @example
891
+ * ```ts
892
+ * // The migration's instruction for this action, or the action's description.
893
+ * const textOf = ({ action, instruction }: Plan.Occurrence) =>
894
+ * instruction?.content
895
+ * .map((part) => (part._tag === "Text" ? part.text : part.action.description))
896
+ * .join("") ?? action.description;
897
+ *
898
+ * const interaction = Interaction.promise(async ({ occurrence }, { signal }) =>
899
+ * (await ask(textOf(occurrence), { signal })) ? "confirmed" : "declined",
900
+ * );
901
+ * ```
902
+ *
903
+ * @since @next
904
+ */
905
+ const promise = (confirm, options) => {
906
+ const adapt = adaptPromise(options ?? {});
907
+ return {
908
+ [TypeId]: TypeId,
909
+ confirm: (request) => adapt((context) => confirm(request, context), (cause) => new UnexpectedInteractionError({
910
+ occurrenceId: request.occurrence.id,
911
+ reason: "rejected",
912
+ cause
913
+ })).pipe(Effect.flatMap(checkAnswer(request)))
914
+ };
915
+ };
916
+ /**
917
+ * Confirms manual work with an Effect, which keeps its own errors and services and
918
+ * stops through Effect interruption when the run is cancelled.
919
+ *
920
+ * @since @next
921
+ */
922
+ const effect = (confirm) => ({
923
+ [TypeId]: TypeId,
924
+ confirm: (request) => Effect.flatMap(Effect.suspend(() => confirm(request)), checkAnswer(request))
925
+ });
730
926
  // src/features/planning/resolve-error.ts
731
927
  /**
732
928
  * The history's declarations are invalid. Resolution needs a valid history.
@@ -2121,6 +2317,6 @@ const withMetadata = (version, metadata) => ({
2121
2317
  version,
2122
2318
  metadata
2123
2319
  });
2124
- export { action_exports as Action, change_exports as Change, executor_exports as Executor, handler_exports as Handler, history_exports as History, migration_exports as Migration, package_exports as Package, plan_exports as Plan, rule_exports as Rule, shortcut_exports as Shortcut, version_exports as Version };
2320
+ export { action_exports as Action, change_exports as Change, executor_exports as Executor, handler_exports as Handler, history_exports as History, interaction_exports as Interaction, migration_exports as Migration, package_exports as Package, plan_exports as Plan, rule_exports as Rule, shortcut_exports as Shortcut, version_exports as Version };
2125
2321
 
2126
2322
  //# sourceMappingURL=index.js.map