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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { Array as Array$1, Cause, Context, Data, Deferred, Duration, Effect, Equal, Exit, Graph, Option, Order, Predicate, Result, Schema, SemVer } from "effect";
2
+ import { Array as Array$1, Cause, Context, Data, Deferred, Duration, Effect, Equal, Exit, Fiber, Graph, Layer, Option, Order, Predicate, Result, Schema, Scope, SemVer } from "effect";
3
3
  import dedentText from "dedent";
4
4
  // src/foundation/action.ts
5
5
  var action_exports = /* @__PURE__ */ __exportAll({
@@ -101,7 +101,7 @@ const describeValue = (value) => {
101
101
  var change_exports = /* @__PURE__ */ __exportAll({
102
102
  define: () => define,
103
103
  isChange: () => isChange,
104
- make: () => make$5
104
+ make: () => make$6
105
105
  });
106
106
  const describe = (id, metadata, relations) => (strings, ...values) => {
107
107
  const literals = dedent(strings);
@@ -122,7 +122,7 @@ const describe = (id, metadata, relations) => (strings, ...values) => {
122
122
  backportOf: relations.backportOf
123
123
  };
124
124
  };
125
- function make$5(id, metadata = {}, relations = {}) {
125
+ function make$6(id, metadata = {}, relations = {}) {
126
126
  return describe(id, metadata, relations);
127
127
  }
128
128
  /**
@@ -144,17 +144,18 @@ function make$5(id, metadata = {}, relations = {}) {
144
144
  *
145
145
  * @since @next
146
146
  */
147
- const define = () => ({ make: make$5 });
147
+ const define = () => ({ make: make$6 });
148
148
  /** @since @next */
149
149
  const isChange = (value) => Predicate.isTagged(value, "Change");
150
150
  // src/features/execution/settlement.ts
151
151
  const SettlementReference = Context.Reference("deltafold/Settlement", { defaultValue: () => ({
152
152
  grace: Duration.zero,
153
- record: () => {}
153
+ unsettled: () => {}
154
154
  }) });
155
155
  /**
156
156
  * Runs a Promise-producing effect. If it is interrupted after the Promise started,
157
- * waits up to the settlement grace period and records whether the Promise settled.
157
+ * waits up to the settlement grace period and hands a still-pending Promise to the
158
+ * settlement, which can hold resources until it settles.
158
159
  */
159
160
  const trackPromise = (start) => Effect.suspend(() => {
160
161
  let pending;
@@ -165,110 +166,171 @@ const trackPromise = (start) => Effect.suspend(() => {
165
166
  return start(capture).pipe(Effect.onInterrupt(() => Effect.gen(function* () {
166
167
  const started = pending;
167
168
  if (started === void 0) return;
169
+ const settles = started.then(() => void 0, () => void 0);
168
170
  const settlement = yield* SettlementReference;
169
- const settled = yield* Effect.promise(() => started.then(() => void 0, () => void 0)).pipe(Effect.timeoutOption(settlement.grace));
170
- settlement.record(Option.isSome(settled));
171
+ const settled = yield* Effect.promise(() => settles).pipe(Effect.timeoutOption(settlement.grace));
172
+ if (Option.isNone(settled)) settlement.unsettled(settles);
171
173
  })));
172
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
+ };
173
194
  // src/features/execution/handler.ts
174
195
  var handler_exports = /* @__PURE__ */ __exportAll({
175
196
  UnexpectedHandlerError: () => UnexpectedHandlerError,
176
- effect: () => effect$1,
197
+ VerificationFailed: () => VerificationFailed,
198
+ effect: () => effect$2,
177
199
  isHandler: () => isHandler,
178
- promise: () => promise
200
+ manual: () => manual,
201
+ manualEffect: () => manualEffect,
202
+ prepared: () => prepared,
203
+ promise: () => promise$1,
204
+ skip: () => skip
179
205
  });
180
206
  /**
181
- * A Promise handler rejected or threw a value that none of its declared error guards
182
- * recognized.
207
+ * A person confirmed manual work, and the handler's `verify` check returned `false`.
183
208
  *
184
209
  * @since @next
185
210
  */
186
- var UnexpectedHandlerError = class extends Data.TaggedError("UnexpectedHandlerError") {
211
+ var VerificationFailed = class extends Data.TaggedError("VerificationFailed") {
187
212
  get message() {
188
- return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase}`;
213
+ return `Manual work for action "${this.actionId}" was confirmed, but its verification check did not pass`;
189
214
  }
190
215
  };
191
- const TypeId = "~deltafold/Handler";
192
- /** @since @next */
193
- const isHandler = (value) => Predicate.hasProperty(value, TypeId);
194
- const skipReasonOf = (action, reason) => {
195
- if (reason === void 0) return "Precondition returned false";
196
- return typeof reason === "string" ? reason : reason(action.payload);
197
- };
198
- const declaredError = (guards) => (cause) => guards.some((guard) => Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause));
199
216
  /**
200
- * Implements an action with Promise callbacks. The callbacks run lazily through
201
- * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services in
202
- * their second argument.
203
- *
204
- * @example
205
- * ```ts
206
- * Handler.promise(
207
- * updateRemoteConfig,
208
- * async (payload, { signal, services: { editor } }) => {
209
- * await editor.update(payload, { signal });
210
- * },
211
- * { services: { editor: ConfigEditor } },
212
- * );
213
- * ```
217
+ * A Promise handler rejected or threw a value that none of its declared error guards
218
+ * recognized, or its prepare phase returned something other than `Handler.prepared` or
219
+ * `Handler.skip`.
214
220
  *
215
221
  * @since @next
216
222
  */
217
- const promise = (action, run, options) => {
218
- const isDeclared = declaredError(options?.errors ?? []);
219
- const services = options?.services ?? {};
220
- const resolve = Effect.map(Effect.context(), (context) => Object.fromEntries(Reflect.ownKeys(services).map((name) => [name, Context.get(context, services[name])])));
221
- const adapt = (phase, callback) => Effect.flatMap(resolve, (resolved) => trackPromise((capture) => Effect.tryPromise({
222
- try: (signal) => capture(Promise.resolve(callback({
223
- signal,
224
- services: resolved
225
- }))),
226
- catch: (cause) => isDeclared(cause) ? cause : new UnexpectedHandlerError({
227
- actionId: action.id,
228
- kind: action.kind,
229
- phase,
230
- cause
231
- })
232
- })));
233
- const when = options?.when;
223
+ var UnexpectedHandlerError = class extends Data.TaggedError("UnexpectedHandlerError") {
224
+ get message() {
225
+ return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase} phase`;
226
+ }
227
+ };
228
+ const PreparationTypeId = "~deltafold/Preparation";
229
+ function prepared(value) {
234
230
  return {
235
- [TypeId]: TypeId,
236
- action,
237
- body: Effect.asVoid(adapt("body", (context) => run(action.payload, context))),
238
- precondition: when === void 0 ? void 0 : adapt("precondition", (context) => when(action.payload, context)),
239
- skipReason: skipReasonOf(action, options?.skipReason)
231
+ [PreparationTypeId]: PreparationTypeId,
232
+ _tag: "Prepared",
233
+ value
240
234
  };
241
- };
235
+ }
242
236
  /**
243
- * Implements an action with an Effect. The body keeps its own errors and services, and
244
- * stops through native Effect interruption.
237
+ * Ends a prepare phase by skipping the occurrence. The apply phase does not run.
245
238
  *
246
239
  * @since @next
247
240
  */
248
- const effect$1 = (action, run, options = {}) => {
249
- const when = options.when;
250
- return {
251
- [TypeId]: TypeId,
252
- action,
253
- body: Effect.asVoid(Effect.suspend(() => run(action.payload))),
254
- precondition: when === void 0 ? void 0 : Effect.suspend(() => when(action.payload)),
255
- skipReason: skipReasonOf(action, options.skipReason)
256
- };
257
- };
241
+ const skip = (reason) => ({
242
+ [PreparationTypeId]: PreparationTypeId,
243
+ _tag: "Skip",
244
+ reason
245
+ });
246
+ const isPreparation = (value) => Predicate.hasProperty(value, PreparationTypeId);
247
+ const notAPreparation = () => /* @__PURE__ */ new TypeError("A prepare phase must return Handler.prepared(value) or Handler.skip(reason)");
248
+ const applyStep = (apply) => ({
249
+ _tag: "Apply",
250
+ apply
251
+ });
252
+ const TypeId$1 = "~deltafold/Handler";
253
+ /** @since @next */
254
+ const isHandler = (value) => Predicate.hasProperty(value, TypeId$1);
255
+ const make$5 = (action, prepares, prepare) => ({
256
+ [TypeId$1]: TypeId$1,
257
+ action,
258
+ performer: "automated",
259
+ prepares,
260
+ prepare
261
+ });
262
+ function promise$1(action, run, options) {
263
+ const adaptCallback = adaptPromise(options ?? {});
264
+ const unexpected = (phase, cause) => new UnexpectedHandlerError({
265
+ actionId: action.id,
266
+ kind: action.kind,
267
+ phase,
268
+ cause
269
+ });
270
+ const adapt = (phase, callback) => adaptCallback(callback, (cause) => unexpected(phase, cause));
271
+ if (Predicate.isFunction(run)) {
272
+ const apply = Effect.asVoid(adapt("apply", (context) => run(action.payload, context)));
273
+ return make$5(action, false, () => Effect.succeed(applyStep(apply)));
274
+ }
275
+ const prepare = adapt("prepare", (context) => run.prepare(action.payload, context)).pipe(Effect.filterOrFail(isPreparation, () => unexpected("prepare", notAPreparation())), Effect.map((preparation) => preparation._tag === "Skip" ? preparation : applyStep(Effect.asVoid(adapt("apply", (context) => run.apply(preparation.value, {
276
+ ...context,
277
+ payload: action.payload
278
+ }))))));
279
+ return make$5(action, true, () => prepare);
280
+ }
281
+ function effect$2(action, run) {
282
+ if (Predicate.isFunction(run)) {
283
+ const apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));
284
+ return make$5(action, false, (scope) => Effect.succeed(applyStep(Scope.provide(apply, scope))));
285
+ }
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)))));
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
+ }
258
319
  // src/features/execution/executor.ts
259
320
  var executor_exports = /* @__PURE__ */ __exportAll({
260
321
  ExecutionFailed: () => ExecutionFailed,
261
322
  ExecutionInterrupted: () => ExecutionInterrupted,
262
323
  HandlerCoverageError: () => HandlerCoverageError,
263
- effect: () => effect,
324
+ InteractionUnavailable: () => InteractionUnavailable,
325
+ effect: () => effect$1,
264
326
  runPromise: () => runPromise
265
327
  });
266
328
  const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
267
329
  /**
268
- * Handler coverage failed before any precondition or body ran. Every occurrence needs
269
- * exactly one handler, for the same action definition: the same identifier, kind, and
270
- * payload. For an occurrence that a rule produced, the issue names the rule and the
271
- * occurrences it replaced.
330
+ * Handler coverage failed before any handler phase ran. Every occurrence needs exactly
331
+ * one handler, for the same action definition: the same identifier, kind, and payload.
332
+ * For an occurrence that a rule produced, the issue names the rule and the occurrences
333
+ * it replaced.
272
334
  *
273
335
  * @since @next
274
336
  */
@@ -277,15 +339,29 @@ var HandlerCoverageError = class extends HandlerCoverageBase {
277
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("; ")}.`;
278
340
  }
279
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(", ");
280
355
  const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
281
356
  /**
282
- * 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.
283
359
  *
284
360
  * @since @next
285
361
  */
286
362
  var ExecutionFailed = class extends ExecutionFailedBase {
287
363
  get message() {
288
- 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.`;
289
365
  }
290
366
  };
291
367
  const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
@@ -360,10 +436,24 @@ const failureOf = (cause) => ({
360
436
  error: Option.getOrUndefined(Cause.findErrorOption(cause)),
361
437
  cause
362
438
  });
439
+ /** The exit an occurrence's scope closes with, so finalizers see how it ended. */
440
+ const exitOf = (outcome) => {
441
+ switch (outcome?._tag) {
442
+ case "Failed":
443
+ case "PreparationFailed": return Exit.failCause(outcome.cause);
444
+ case "Interrupted": return Exit.interrupt();
445
+ default: return Exit.void;
446
+ }
447
+ };
363
448
  const forEachBranch = (branches, concurrency, run) => Effect.forEach(branches, run, {
364
449
  concurrency,
365
450
  discard: true
366
451
  });
452
+ /**
453
+ * Logs a cleanup failure that the report cannot carry, with the occurrence or the
454
+ * services layer that owned the resources.
455
+ */
456
+ const logCleanupFailure = (owner) => (cause) => Effect.logError("deltafold: cleanup failed", cause).pipe(Effect.annotateLogs(owner));
367
457
  /** Admission state, cancellation, and timeouts shared by real and dry runs. */
368
458
  const makeControl = (options, subscribe) => Effect.gen(function* () {
369
459
  const halt = { reason: void 0 };
@@ -372,21 +462,27 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
372
462
  const stop = (reason) => {
373
463
  halt.reason ??= reason;
374
464
  };
465
+ let cancellationArrived = false;
375
466
  subscribe?.(() => {
467
+ cancellationArrived = true;
376
468
  stop("cancelled");
377
469
  Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
378
470
  });
379
- /** Runs one precondition or body, racing it against cancellation and the timeout. */
380
- const runPhase = (work) => Effect.gen(function* () {
471
+ /**
472
+ * Runs one phase, racing it against cancellation and its own timeout. An
473
+ * interrupted Promise that outlives the settlement grace period goes to `unsettled`.
474
+ */
475
+ const runPhase = (work, unsettled, timing = "timed") => Effect.gen(function* () {
381
476
  let settled = true;
382
477
  const tracked = work.pipe(Effect.provideService(SettlementReference, {
383
478
  grace: settleTimeout,
384
- record: (value) => {
385
- settled = value;
479
+ unsettled: (promise) => {
480
+ settled = false;
481
+ unsettled.push(promise);
386
482
  }
387
483
  }));
388
484
  const stopSignals = [Deferred.await(cancelled)];
389
- 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"));
390
486
  const result = yield* Effect.raceFirst(Effect.map(Effect.exit(tracked), (exit) => ({
391
487
  _tag: "Done",
392
488
  exit
@@ -404,92 +500,155 @@ const makeControl = (options, subscribe) => Effect.gen(function* () {
404
500
  return {
405
501
  halt,
406
502
  stop,
407
- runPhase
503
+ runPhase,
504
+ isCancelled: () => cancellationArrived
408
505
  };
409
506
  });
507
+ /**
508
+ * Runs one occurrence in its own scope, which both phases share. `use` returns the
509
+ * exit to close the scope with. The scope closes as soon as the occurrence ends, and
510
+ * a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not
511
+ * settled, the scope stays open until it does, possibly forever; a failing
512
+ * finalizer is then logged, because the report may already have been returned.
513
+ */
514
+ const inScope = (retain, occurrenceId, use, onCleanupFailure) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
515
+ const scope = yield* Scope.make();
516
+ const unsettled = [];
517
+ const used = yield* Effect.exit(restore(use(scope, unsettled)));
518
+ const end = Exit.isSuccess(used) ? used.value : used;
519
+ if (unsettled.length > 0) retain(yield* Effect.forkDetach(Effect.promise(() => Promise.all(unsettled)).pipe(Effect.andThen(Scope.close(scope, end)), Effect.catchCause(logCleanupFailure({ occurrence: occurrenceId })))));
520
+ else {
521
+ const closed = yield* Effect.exit(Scope.close(scope, end));
522
+ if (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);
523
+ }
524
+ return yield* used;
525
+ })).pipe(Effect.asVoid);
410
526
  const interrupted = (plan, mode, reason, outcomes, bodiesStarted) => new ExecutionInterrupted({
411
527
  reason,
412
528
  report: report(plan, mode, "interrupted", outcomes, bodiesStarted)
413
529
  });
414
- const execute = (plan, resolved, options, subscribe) => Effect.gen(function* () {
530
+ /**
531
+ * The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
532
+ * handler that interrupted itself stops admission.
533
+ */
534
+ const unsuccessful = (phase, result, stop) => {
535
+ if (result._tag === "Interrupted") return {
536
+ _tag: "Interrupted",
537
+ phase,
538
+ reason: result.reason,
539
+ settled: result.settled
540
+ };
541
+ if (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {
542
+ stop("handler");
543
+ return {
544
+ _tag: "Interrupted",
545
+ phase,
546
+ reason: "handler",
547
+ settled: true
548
+ };
549
+ }
550
+ };
551
+ const execute = (plan, resolved, interaction, options, subscribe, retain) => Effect.gen(function* () {
415
552
  const outcomes = /* @__PURE__ */ new Map();
416
- const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
553
+ const { halt, stop, runPhase, isCancelled } = yield* makeControl(options, subscribe);
417
554
  let bodiesStarted = false;
418
- const runOccurrence = (occurrence) => Effect.gen(function* () {
419
- if (halt.reason !== void 0) return;
555
+ const runOccurrence = (occurrence) => {
556
+ if (halt.reason !== void 0) return Effect.void;
420
557
  const handler = resolved.get(occurrence.id);
421
- if (handler === void 0) return;
422
- if (handler.precondition !== void 0) {
423
- const checked = yield* runPhase(handler.precondition);
424
- if (checked._tag === "Interrupted") {
425
- outcomes.set(occurrence.id, {
426
- _tag: "Interrupted",
427
- phase: "precondition",
428
- reason: checked.reason,
429
- settled: checked.settled
430
- });
431
- return;
558
+ if (handler === void 0) return Effect.void;
559
+ let phase = "prepare";
560
+ const end = (outcome) => {
561
+ outcomes.set(occurrence.id, outcome);
562
+ return exitOf(outcome);
563
+ };
564
+ const fail = (cause) => {
565
+ stop("failure");
566
+ return end({
567
+ _tag: "Failed",
568
+ phase,
569
+ ...failureOf(cause)
570
+ });
571
+ };
572
+ const use = (scope, unsettled) => Effect.gen(function* () {
573
+ let step;
574
+ if (handler.prepares) {
575
+ const preparation = yield* runPhase(handler.prepare(scope), unsettled);
576
+ const stopped = unsuccessful("prepare", preparation, stop);
577
+ if (stopped !== void 0) return end(stopped);
578
+ if (preparation._tag !== "Done") return Exit.void;
579
+ if (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);
580
+ step = preparation.exit.value;
581
+ if (step._tag === "Apply" && halt.reason === "cancelled") return Exit.void;
582
+ } else {
583
+ const started = yield* Effect.exit(handler.prepare(scope));
584
+ if (Exit.isFailure(started)) return fail(started.cause);
585
+ step = started.value;
432
586
  }
433
- if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
434
- stop("handler");
435
- outcomes.set(occurrence.id, {
587
+ if (step._tag === "Skip") return end({
588
+ _tag: "Skipped",
589
+ reason: step.reason
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({
436
611
  _tag: "Interrupted",
437
- phase: "precondition",
438
- reason: "handler",
612
+ phase,
613
+ reason: "cancelled",
439
614
  settled: true
440
615
  });
441
- return;
442
- }
443
- if (Exit.isFailure(checked.exit)) {
444
- stop("failure");
445
- outcomes.set(occurrence.id, {
446
- _tag: "Failed",
447
- phase: "precondition",
448
- ...failureOf(checked.exit.cause)
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"
449
625
  });
450
- return;
451
626
  }
452
- if (!checked.exit.value) {
453
- outcomes.set(occurrence.id, {
454
- _tag: "Skipped",
455
- reason: handler.skipReason
456
- });
457
- return;
458
- }
459
- if (halt.reason === "cancelled") return;
460
- }
461
- bodiesStarted = true;
462
- const ran = yield* runPhase(handler.body);
463
- if (ran._tag === "Interrupted") {
464
- outcomes.set(occurrence.id, {
465
- _tag: "Interrupted",
466
- phase: "body",
467
- reason: ran.reason,
468
- settled: ran.settled
469
- });
470
- return;
471
- }
472
- if (Exit.isFailure(ran.exit) && Cause.hasInterruptsOnly(ran.exit.cause)) {
473
- stop("handler");
474
- outcomes.set(occurrence.id, {
475
- _tag: "Interrupted",
476
- phase: "body",
477
- reason: "handler",
478
- settled: true
627
+ phase = "apply";
628
+ bodiesStarted = true;
629
+ const applied = yield* runPhase(step.apply, unsettled);
630
+ const stopped = unsuccessful("apply", applied, stop);
631
+ if (stopped !== void 0) return end(stopped);
632
+ if (applied._tag !== "Done") return Exit.void;
633
+ if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
634
+ return end({
635
+ _tag: "Completed",
636
+ performer: "automated"
479
637
  });
480
- return;
481
- }
482
- if (Exit.isFailure(ran.exit)) {
638
+ });
639
+ const onCleanupFailure = (cause) => Effect.suspend(() => {
640
+ const outcome = outcomes.get(occurrence.id);
641
+ if (outcome?._tag === "Interrupted") return logCleanupFailure({ occurrence: occurrence.id })(cause);
483
642
  stop("failure");
484
643
  outcomes.set(occurrence.id, {
485
644
  _tag: "Failed",
486
- phase: "body",
487
- ...failureOf(ran.exit.cause)
645
+ phase,
646
+ ...failureOf(outcome?._tag === "Failed" ? Cause.combine(outcome.cause, cause) : cause)
488
647
  });
489
- return;
490
- }
491
- outcomes.set(occurrence.id, { _tag: "Completed" });
492
- });
648
+ return Effect.void;
649
+ });
650
+ return inScope(retain, occurrence.id, use, onCleanupFailure);
651
+ };
493
652
  const runNode = (node) => {
494
653
  switch (node._tag) {
495
654
  case "Occurrence": return runOccurrence(node);
@@ -506,15 +665,56 @@ const execute = (plan, resolved, options, subscribe) => Effect.gen(function* ()
506
665
  const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
507
666
  return yield* new ExecutionFailed({
508
667
  failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
668
+ declined: result.occurrences.filter((entry) => entry.outcome._tag === "Declined"),
509
669
  report: result
510
670
  });
511
671
  }
512
672
  return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
513
673
  });
514
- const dryRun = (plan, resolved, options, subscribe) => Effect.gen(function* () {
674
+ const dryRun = (plan, resolved, options, subscribe, retain) => Effect.gen(function* () {
515
675
  const outcomes = /* @__PURE__ */ new Map();
516
676
  const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
517
677
  let failedAt;
678
+ /** Runs a prepare phase in the occurrence's scope and records what it predicts. */
679
+ const prepare = (id, handler) => {
680
+ const end = (outcome) => {
681
+ outcomes.set(id, outcome);
682
+ return exitOf(outcome);
683
+ };
684
+ const use = (scope, unsettled) => Effect.gen(function* () {
685
+ const preparation = yield* runPhase(handler.prepare(scope), unsettled);
686
+ const stopped = unsuccessful("prepare", preparation, stop);
687
+ if (stopped !== void 0) return end(stopped);
688
+ if (preparation._tag !== "Done") return Exit.void;
689
+ if (Exit.isFailure(preparation.exit)) {
690
+ failedAt = id;
691
+ return end({
692
+ _tag: "PreparationFailed",
693
+ ...failureOf(preparation.exit.cause)
694
+ });
695
+ }
696
+ const step = preparation.exit.value;
697
+ return end(step._tag === "Skip" ? {
698
+ _tag: "WouldSkip",
699
+ reason: step.reason
700
+ } : {
701
+ _tag: "WouldExecute",
702
+ evaluated: true,
703
+ performer: handler.performer
704
+ });
705
+ });
706
+ const onCleanupFailure = (cause) => Effect.suspend(() => {
707
+ const outcome = outcomes.get(id);
708
+ if (outcome?._tag === "Interrupted") return logCleanupFailure({ occurrence: id })(cause);
709
+ failedAt ??= id;
710
+ outcomes.set(id, {
711
+ _tag: "PreparationFailed",
712
+ ...failureOf(outcome?._tag === "PreparationFailed" ? Cause.combine(outcome.cause, cause) : cause)
713
+ });
714
+ return Effect.void;
715
+ });
716
+ return inScope(retain, id, use, onCleanupFailure);
717
+ };
518
718
  /** Returns whether the node would or might change state. */
519
719
  const visit = (node, dirty) => Effect.gen(function* () {
520
720
  if (node._tag === "Sequence") {
@@ -532,86 +732,64 @@ const dryRun = (plan, resolved, options, subscribe) => Effect.gen(function* () {
532
732
  if (failedAt !== void 0) {
533
733
  outcomes.set(node.id, {
534
734
  _tag: "Undetermined",
535
- reason: `Execution would stop at the failed precondition of "${failedAt}".`
735
+ reason: `Execution would stop at the failed preparation of "${failedAt}".`,
736
+ performer: handler.performer
536
737
  });
537
738
  return true;
538
739
  }
539
- if (handler.precondition === void 0) {
740
+ if (!handler.prepares) {
540
741
  outcomes.set(node.id, {
541
742
  _tag: "WouldExecute",
542
- evaluated: false
743
+ evaluated: false,
744
+ performer: handler.performer
543
745
  });
544
746
  return true;
545
747
  }
546
748
  if (dirty) {
547
749
  outcomes.set(node.id, {
548
750
  _tag: "Undetermined",
549
- reason: "The precondition depends on earlier actions that a dry run does not apply."
550
- });
551
- return true;
552
- }
553
- const checked = yield* runPhase(handler.precondition);
554
- if (checked._tag === "Interrupted") {
555
- outcomes.set(node.id, {
556
- _tag: "Interrupted",
557
- phase: "precondition",
558
- reason: checked.reason,
559
- settled: checked.settled
560
- });
561
- return true;
562
- }
563
- if (Exit.isFailure(checked.exit) && Cause.hasInterruptsOnly(checked.exit.cause)) {
564
- stop("handler");
565
- outcomes.set(node.id, {
566
- _tag: "Interrupted",
567
- phase: "precondition",
568
- reason: "handler",
569
- settled: true
570
- });
571
- return true;
572
- }
573
- if (Exit.isFailure(checked.exit)) {
574
- failedAt = node.id;
575
- outcomes.set(node.id, {
576
- _tag: "PreconditionFailed",
577
- ...failureOf(checked.exit.cause)
751
+ reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
752
+ performer: handler.performer
578
753
  });
579
754
  return true;
580
755
  }
581
- if (!checked.exit.value) {
582
- outcomes.set(node.id, {
583
- _tag: "WouldSkip",
584
- reason: handler.skipReason
585
- });
586
- return false;
587
- }
588
- outcomes.set(node.id, {
589
- _tag: "WouldExecute",
590
- evaluated: true
591
- });
592
- return true;
756
+ yield* prepare(node.id, handler);
757
+ return outcomes.get(node.id)?._tag !== "WouldSkip";
593
758
  });
594
759
  let dirty = false;
595
760
  for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
596
761
  if (halt.reason !== void 0 && halt.reason !== "failure") return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
597
762
  return report(plan, "dry-run", failedAt === void 0 ? "would-complete" : "would-fail", outcomes, false);
598
763
  });
599
- const run = (plan, options, subscribe) => {
764
+ const run = (plan, options, subscribe, retain) => {
600
765
  const handlers = options.handlers ?? [];
766
+ const interaction = options.interaction;
601
767
  return Effect.gen(function* () {
602
768
  const checked = coverage(plan, handlers);
603
769
  if (checked.issues.length > 0) return yield* new HandlerCoverageError({
604
770
  issues: checked.issues,
605
771
  report: report(plan, options.dryRun === true ? "dry-run" : "execute", "not-started", /* @__PURE__ */ new Map(), false)
606
772
  });
607
- return options.dryRun === true ? yield* dryRun(plan, checked.resolved, options, subscribe) : yield* execute(plan, checked.resolved, options, subscribe);
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);
608
780
  });
609
781
  };
610
782
  /**
611
- * Runs a plan as an Effect. Coverage is checked before any precondition or body runs.
612
- * Steps are sequential barriers; parallel groups run their branches concurrently. On
613
- * failure, no new action starts, and actions already running settle before the effect
614
- * fails with the partial report.
783
+ * Runs a plan as an Effect. Coverage, and the interaction that manual handlers need,
784
+ * are checked before any handler phase runs. Steps
785
+ * are sequential barriers; parallel groups run their branches concurrently. On failure,
786
+ * no new action starts, and actions already running settle before the effect fails
787
+ * with the partial report.
788
+ *
789
+ * Each occurrence has its own scope, shared by its phases and closed when it ends. An
790
+ * interrupted Promise that has not settled keeps its occurrence's scope open until it
791
+ * settles, after the effect has ended. Services that the caller provides stay the
792
+ * caller's to release.
615
793
  *
616
794
  * To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
617
795
  * signal passed to Promise callbacks. The effect then ends as interrupted, without a
@@ -619,17 +797,20 @@ const run = (plan, options, subscribe) => {
619
797
  *
620
798
  * @since @next
621
799
  */
622
- const effect = (plan, options) => run(plan, options, void 0);
800
+ const effect$1 = (plan, options) => run(plan, options, void 0, () => {});
623
801
  /**
624
802
  * Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
625
- * `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
803
+ * `InteractionUnavailable`, `ExecutionFailed`, or `ExecutionInterrupted`, each carrying
804
+ * the partial report.
626
805
  * Building a supplied services layer can also reject with the layer's own error,
627
806
  * without a report.
628
807
  *
629
- * A services layer is built for this run and finalized when the run ends. A services
630
- * context stays owned by the caller. A Promise callback that ignores its signal can keep
631
- * running after cancellation or a timeout, beyond `settleTimeout`, and so after the
632
- * run's layer resources are finalized; the report marks it as possibly still running.
808
+ * A services layer is built for this run. A services context stays owned by the
809
+ * caller. A Promise callback that ignores its signal can keep running after
810
+ * cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly
811
+ * still running. Its occurrence's scope and the run's services layer then stay open
812
+ * until it settles, possibly forever, and close in that order. A cleanup failure after
813
+ * the Promise resolved is logged through Effect.
633
814
  *
634
815
  * @since @next
635
816
  */
@@ -647,18 +828,101 @@ const runPromise = (plan, options) => {
647
828
  else cancelRun();
648
829
  };
649
830
  signal?.addEventListener("abort", onAbort, { once: true });
650
- const program = run(plan, options, signal === void 0 ? void 0 : (cancel) => {
831
+ const subscribe = signal === void 0 ? void 0 : (cancel) => {
651
832
  cancelRun = cancel;
652
833
  if (signal.aborted) cancel();
653
- });
834
+ };
835
+ const retained = [];
836
+ const program = run(plan, options, subscribe, (fiber) => retained.push(fiber));
654
837
  const services = options.services;
655
- const provided = services === void 0 ? program : Context.isContext(services) ? Effect.provideContext(program, services) : Effect.provide(program, services);
838
+ const provided = services === void 0 ? program : Context.isContext(services) ? Effect.provideContext(program, services) : Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
839
+ const scope = yield* Scope.make();
840
+ const built = yield* Effect.exit(restore(Layer.buildWithScope(services, scope)));
841
+ if (Exit.isFailure(built)) {
842
+ yield* Scope.close(scope, built);
843
+ return yield* built;
844
+ }
845
+ const exit = yield* Effect.exit(restore(Effect.provideContext(program, built.value)));
846
+ if (retained.length === 0) yield* Scope.close(scope, exit);
847
+ else yield* Effect.forkDetach(Fiber.awaitAll(retained).pipe(Effect.andThen(Scope.close(scope, exit)), Effect.catchCause(logCleanupFailure({ owner: "services layer" }))));
848
+ return yield* exit;
849
+ }));
656
850
  const cancellable = signal === void 0 ? provided : Effect.raceFirst(provided, Effect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())));
657
851
  return Effect.runPromiseExit(cancellable).finally(() => signal?.removeEventListener("abort", onAbort)).then((exit) => {
658
852
  if (Exit.isSuccess(exit)) return exit.value;
659
853
  throw Cause.squash(exit.cause);
660
854
  });
661
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
+ });
662
926
  // src/features/planning/resolve-error.ts
663
927
  /**
664
928
  * The history's declarations are invalid. Resolution needs a valid history.
@@ -2053,6 +2317,6 @@ const withMetadata = (version, metadata) => ({
2053
2317
  version,
2054
2318
  metadata
2055
2319
  });
2056
- 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 };
2057
2321
 
2058
2322
  //# sourceMappingURL=index.js.map