@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 1,504 lines 60.6 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Context from "effect/Context";
3 import * as Data from "effect/Data";
4 import * as DateTime from "effect/DateTime";
5 import * as Deferred from "effect/Deferred";
6 import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import * as Formatter from "effect/Formatter";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Redacted from "effect/Redacted";
13 import * as Schema from "effect/Schema";
14 import type { DurableDeferred, WorkflowEngine } from "effect/workflow";
15 import * as Aggregate from "./Aggregate.ts";
16 import type * as Command from "./Command.ts";
17 import * as ExternalSystem from "./ExternalSystem.ts";
18 import * as InMemory from "./InMemory.ts";
19 import type * as Key from "./Key.ts";
20 import * as Model from "./Model.ts";
21 import type * as Saga from "./Saga.ts";
22 import type * as DomainStream from "./Stream.ts";
23 import type * as View from "./View.ts";
24
25 /** How far a story got with one step. */
26 export interface StepReport {
27 /** The step's number, from 1. */
28 readonly step: number;
29 /** The step's kind: `Given`, `When`, `Then`, ... */
30 readonly kind: Step["_tag"];
31 readonly status: "passed" | "failed" | "not-run";
32 /** A one-line summary of the step. Redacted values print as `<redacted>`. */
33 readonly summary: string;
34 }
35
36 /**
37 * A failed story expectation. `message` starts with `reason`, then lists every
38 * step (✓ passed, ✗ failed, blank: not run) and the events each touched
39 * aggregate committed so far.
40 */
41 export class StoryFailure extends Data.TaggedError("StoryFailure")<{
42 /** The step that failed (the last step for a failure at the end of the story). */
43 readonly step: number;
44 readonly message: string;
45 /** Why the story failed, without the step list. */
46 readonly reason: string;
47 readonly steps: ReadonlyArray<StepReport>;
48 /** The tags of the events committed so far, per touched aggregate (`Aggregate/id`). */
49 readonly events: Readonly<Record<string, ReadonlyArray<string>>>;
50 }> {}
51
52 /** A failure inside the runner, before it is turned into a {@link StoryFailure}. */
53 class StepFailed extends Data.TaggedError("StepFailed")<{
54 readonly step: number;
55 readonly message: string;
56 /** The failure is about the whole story, not one step. */
57 readonly atEnd?: boolean;
58 /** What the step expected and what it got, as short summaries. */
59 readonly expected?: string;
60 readonly actual?: string;
61 /** What the expected / actual pair is about, e.g. `Counter/c-1`. */
62 readonly label?: string;
63 /** A line to print under the failed step. */
64 readonly detail?: string;
65 }> {}
66
67 /** Marker for "the view key does not exist". */
68 const none: unique symbol = Symbol.for("alchemy/Domain/Story.none") as any;
69
70 /**
71 * One step of a story. Build steps with the step constructors in this module.
72 */
73 export type Step =
74 | {
75 readonly _tag: "Given";
76 readonly ref: Aggregate.Ref;
77 readonly events: ReadonlyArray<{ readonly _tag: string }>;
78 }
79 | {
80 readonly _tag: "When";
81 readonly ref: Aggregate.Ref;
82 readonly command: { readonly _tag: string };
83 readonly commandId?: string;
84 }
85 | {
86 readonly _tag: "Then";
87 readonly ref: Aggregate.Ref;
88 readonly events: ReadonlyArray<{ readonly _tag: string }>;
89 }
90 | { readonly _tag: "Rejected"; readonly rejection: { readonly _tag: string } }
91 | { readonly _tag: "Replied"; readonly reply: unknown }
92 | { readonly _tag: "State"; readonly ref: Aggregate.Ref; readonly expected: unknown }
93 | {
94 readonly _tag: "View";
95 readonly view: View.Any;
96 /** A ref, or the value of a Schema key. */
97 readonly key: Key.RefOf<Key.Any>;
98 readonly expected: unknown;
99 }
100 | {
101 readonly _tag: "Emitted";
102 readonly view: View.Any;
103 /** A ref, or the value of a Schema key. */
104 readonly key: Key.RefOf<Key.Any>;
105 readonly expected: unknown;
106 }
107 | {
108 readonly _tag: "Streamed";
109 readonly stream: DomainStream.Any;
110 /** A ref, or the value of a Schema key. */
111 readonly key: Key.RefOf<Key.Any>;
112 readonly events: ReadonlyArray<{ readonly _tag: string }>;
113 }
114 | {
115 readonly _tag: "Call";
116 readonly tag: string | undefined;
117 readonly op: ExternalSystem.Op;
118 readonly args: unknown;
119 }
120 | {
121 readonly _tag: "Answer";
122 readonly tag: string | undefined;
123 readonly op: ExternalSystem.Op;
124 readonly exit: Exit.Exit<unknown, unknown>;
125 }
126 | {
127 readonly _tag: "Returned";
128 readonly tag: string | undefined;
129 readonly op: ExternalSystem.Op;
130 readonly expected:
131 | { readonly _tag: "Success"; readonly value: unknown }
132 | { readonly _tag: "Failure"; readonly error: unknown }
133 | { readonly _tag: "Died" };
134 }
135 | { readonly _tag: "Clock"; readonly at: string | number | DateTime.DateTime }
136 | { readonly _tag: "Advance"; readonly by: Duration.Input }
137 | {
138 readonly _tag: "Signal";
139 readonly saga: Saga.Any;
140 readonly key: unknown;
141 readonly deferred: DurableDeferred.Any;
142 readonly value: unknown;
143 }
144 | {
145 readonly _tag: "Saga";
146 readonly saga: Saga.Any;
147 readonly key: unknown;
148 readonly expected: Saga.Status<unknown, unknown> | { readonly _tag: "Died" };
149 }
150 | {
151 readonly _tag: "Provide";
152 readonly service: Context.Key<unknown, unknown>;
153 readonly value: unknown;
154 };
155
156 /** The step with this `_tag`. */
157 export type StepOf<Tag extends Step["_tag"]> = Extract<Step, { readonly _tag: Tag }>;
158
159 /**
160 * A `when` step. Its type carries the command's class, so the steps after it
161 * are checked against what the command declares.
162 */
163 export interface WhenStep<C = unknown> extends StepOf<"When"> {
164 readonly "~command"?: C;
165 }
166
167 /** A `rejected` step; its type carries the rejection. */
168 export interface RejectedStep<R = unknown> extends StepOf<"Rejected"> {
169 readonly "~rejection"?: R;
170 }
171
172 /** A `replied` step; its type carries the reply. */
173 export interface RepliedStep<A = unknown> extends StepOf<"Replied"> {
174 readonly "~reply"?: A;
175 }
176
177 /** A `provide` step; its type carries the service it provides. */
178 export interface ProvideStep<I = unknown> extends StepOf<"Provide"> {
179 readonly "~provides"?: I;
180 }
181
182 type CommandClassOf<A extends Aggregate.Any, Cmd> = Extract<
183 A["definition"]["commands"][number],
184 { readonly tag: Cmd extends { readonly _tag: infer T } ? T : never }
185 >;
186 type RejectionOf<C extends Command.Any> = Aggregate.InstanceOf<C["rejects"][number]>;
187 type ReplyOf<C extends Command.Any> = C["reply"] extends Schema.Top ? C["reply"]["Type"] : void;
188 type NameOf<X, Key extends string, Fallback extends string> = X extends {
189 readonly [K in Key]: infer N extends string;
190 }
191 ? N
192 : Fallback;
193
194 /** What a `when` step must be: an error message when a service it needs is not provided yet. */
195 type CheckWhen<H, K extends Command.Any, P> = [Exclude<Command.ContextOf<K>, P>] extends [never]
196 ? H
197 : `${K["tag"]} needs Story.provide(${NameOf<Exclude<Command.ContextOf<K>, P>, "key", "its service">}) before it`;
198
199 /** What a `rejected` step must be: an error message when the last command does not declare it. */
200 type CheckRejected<H, R, C> = C extends Command.Any
201 ? [R] extends [RejectionOf<C>]
202 ? H
203 : `${C["tag"]} does not reject with ${NameOf<R, "_tag", "this rejection">}`
204 : H;
205
206 /** What a `replied` step must be: the last command's reply, or an error message when it declares none. */
207 type CheckReplied<H, A, C> = C extends Command.Any
208 ? [A] extends [ReplyOf<C>]
209 ? H
210 : C["reply"] extends Schema.Top
211 ? RepliedStep<ReplyOf<C>>
212 : `${C["tag"]} declares no reply`
213 : H;
214
215 /**
216 * The steps of a story, checked in order: a `rejected` step takes only a
217 * rejection the last `when` command declares, a `replied` step only its reply
218 * type, and a `when` needs a `provide` step before it for every service its
219 * command's middleware provides. A failing step is replaced by a message
220 * saying what is wrong, so the type error names it. A step typed as plain
221 * {@link Step} turns the checks off until the next `when`, since it may be any
222 * step.
223 */
224 export type Checked<
225 S extends ReadonlyArray<Step>,
226 C = unknown,
227 P = never,
228 Out extends ReadonlyArray<unknown> = [],
229 > = S extends readonly [infer H extends Step, ...infer T extends ReadonlyArray<Step>]
230 ? [H] extends [WhenStep<infer K>]
231 ? K extends Command.Any
232 ? Checked<T, K, P, [...Out, CheckWhen<H, K, P>]>
233 : Checked<T, unknown, P, [...Out, H]>
234 : [H] extends [ProvideStep<infer I>]
235 ? Checked<T, C, P | I, [...Out, H]>
236 : [H] extends [RejectedStep<infer R>]
237 ? Checked<T, C, P, [...Out, CheckRejected<H, R, C>]>
238 : [H] extends [RepliedStep<infer A>]
239 ? Checked<T, C, P, [...Out, CheckReplied<H, A, C>]>
240 : [Step] extends [H]
241 ? Checked<T, unknown, any, [...Out, H]>
242 : Checked<T, C, P, [...Out, H]>
243 : [...Out, ...S];
244
245 /** History: events already committed on a stream before the story starts. */
246 const given = <A extends Aggregate.Any>(
247 ref: Aggregate.Ref<A>,
248 ...events: ReadonlyArray<Aggregate.EventOf<A>>
249 ): StepOf<"Given"> => ({
250 _tag: "Given",
251 ref,
252 events: events as ReadonlyArray<{ readonly _tag: string }>,
253 });
254
255 /** Send a command. Its policies run until they finish or suspend on an external system call. */
256 const when = <A extends Aggregate.Any, Cmd extends Aggregate.CommandOf<A>>(
257 ref: Aggregate.Ref<A>,
258 command: Cmd,
259 options?: { readonly commandId?: string },
260 ): WhenStep<CommandClassOf<A, Cmd>> => ({
261 _tag: "When",
262 ref,
263 command: command as { readonly _tag: string },
264 commandId: options?.commandId,
265 });
266
267 /** The next events committed on a stream. With no events: nothing new was committed. */
268 const then = <A extends Aggregate.Any>(
269 ref: Aggregate.Ref<A>,
270 ...events: ReadonlyArray<Aggregate.EventOf<A>>
271 ): StepOf<"Then"> => ({
272 _tag: "Then",
273 ref,
274 events: events as ReadonlyArray<{ readonly _tag: string }>,
275 });
276
277 /**
278 * The last command was rejected with exactly this rejection. It must be one
279 * the last `when` command declares in `rejects`.
280 */
281 const rejected = <R extends { readonly _tag: string }>(rejection: R): RejectedStep<R> => ({
282 _tag: "Rejected",
283 rejection,
284 });
285
286 /** The last command's reply, of the type the last `when` command declares. */
287 const replied = <A>(reply: A): RepliedStep<A> => ({ _tag: "Replied", reply });
288
289 /** Assert on an aggregate instance's current state: an expected (partial) state, or a function. */
290 const state = <A extends Aggregate.Any>(
291 ref: Aggregate.Ref<A>,
292 expected: Partial<Aggregate.StateOf<A>> | ((state: Aggregate.StateOf<A>) => void),
293 ): StepOf<"State"> => ({ _tag: "State", ref, expected });
294
295 /** Assert on a view key: an expected (partial) state, a function, or {@link none}. */
296 const view = <V extends View.Any>(
297 view: V,
298 key: Key.RefOf<View.KeyOf<V>>,
299 expected: Partial<View.StateOf<V>> | ((state: View.StateOf<V>) => void) | typeof none,
300 ): StepOf<"View"> => ({ _tag: "View", view, key, expected });
301
302 /**
303 * Assert on every event a view key has emitted: the expected (partial) events
304 * in order, or a function over the entries (each event with the state after it).
305 */
306 const emitted = <V extends View.Any>(
307 view: V,
308 key: Key.RefOf<View.KeyOf<V>>,
309 expected:
310 | ReadonlyArray<Partial<View.EventOf<V>>>
311 | ((entries: ReadonlyArray<View.Entry<View.StateOf<V>, View.EventOf<V>>>) => void),
312 ): StepOf<"Emitted"> => ({ _tag: "Emitted", view, key, expected });
313
314 /**
315 * The next entries appended to a stream key (by its projection). With no
316 * events: nothing new was appended.
317 */
318 const streamed = <S extends DomainStream.Any>(
319 stream: S,
320 key: Key.RefOf<DomainStream.KeyOf<S>>,
321 ...events: ReadonlyArray<DomainStream.EventOf<S>>
322 ): StepOf<"Streamed"> => ({
323 _tag: "Streamed",
324 stream,
325 key,
326 events: events as ReadonlyArray<{ readonly _tag: string }>,
327 });
328
329 /**
330 * A call to an external system was made with these (partial) arguments:
331 * `Story.call(Payments.refund, { settlementId: "st_1" })`. Every call needs
332 * one: a stubbed call before it's answered, a real call before it's asserted.
333 * Each call is matched once, earliest first. With a tag first, the tag names
334 * that call, so a later step can answer or assert exactly it.
335 */
336 const callStep: {
337 <Args>(op: ExternalSystem.Op<Args, any>, args: Partial<Args>): StepOf<"Call">;
338 <Args>(tag: string, op: ExternalSystem.Op<Args, any>, args: Partial<Args>): StepOf<"Call">;
339 } = (...a: ReadonlyArray<any>): StepOf<"Call"> =>
340 typeof a[0] === "string"
341 ? { _tag: "Call", tag: a[0], op: a[1], args: a[2] }
342 : { _tag: "Call", tag: undefined, op: a[0], args: a[1] };
343
344 /** Answer a pending call with an exit; the tag, when given, comes first. */
345 const answer = (
346 a: ReadonlyArray<any>,
347 exit: (value: any) => Exit.Exit<unknown, unknown>,
348 ): StepOf<"Answer"> =>
349 typeof a[0] === "string"
350 ? { _tag: "Answer", tag: a[0], op: a[1], exit: exit(a[2]) }
351 : { _tag: "Answer", tag: undefined, op: a[0], exit: exit(a[1]) };
352
353 /**
354 * Answer an external system call a `call` step has checked. With a tag
355 * first, answers the call a `call` step tagged; without one, answers the only
356 * pending call to the operation, and fails if several are pending.
357 */
358 const succeed: {
359 <Success>(op: ExternalSystem.Op<any, Success>, value: Success): StepOf<"Answer">;
360 <Success>(tag: string, op: ExternalSystem.Op<any, Success>, value: Success): StepOf<"Answer">;
361 } = (...a: ReadonlyArray<any>): StepOf<"Answer"> => answer(a, Exit.succeed);
362
363 /**
364 * Fail an external system call with one of the operation's declared errors,
365 * as when the vendor refuses. Finds the call the same way `succeed` does.
366 */
367 const fail: {
368 <Error>(op: ExternalSystem.Op<any, any, Error>, error: NoInfer<Error>): StepOf<"Answer">;
369 <Error>(
370 tag: string,
371 op: ExternalSystem.Op<any, any, Error>,
372 error: NoInfer<Error>,
373 ): StepOf<"Answer">;
374 } = (...a: ReadonlyArray<any>): StepOf<"Answer"> => answer(a, Exit.fail);
375
376 /**
377 * Fail an external system call with a defect, as when the transport breaks.
378 * Finds the call the same way `succeed` does.
379 */
380 const die: {
381 (op: ExternalSystem.Op, defect: unknown): StepOf<"Answer">;
382 (tag: string, op: ExternalSystem.Op, defect: unknown): StepOf<"Answer">;
383 } = (...a: ReadonlyArray<any>): StepOf<"Answer"> => answer(a, Exit.die);
384
385 /** Assert how a real call to a system that is not stubbed ended; the tag, when given, comes first. */
386 const outcome = (a: ReadonlyArray<any>, expected: (value: any) => any): StepOf<"Returned"> =>
387 typeof a[0] === "string"
388 ? { _tag: "Returned", tag: a[0], op: a[1], expected: expected(a[2]) }
389 : { _tag: "Returned", tag: undefined, op: a[0], expected: expected(a[1]) };
390
391 /**
392 * A real call to an external system that is not stubbed returned this value.
393 * Finds the call the way `succeed` does: by tag, or the only unasserted call
394 * to the operation. Every real call needs a `call` step, then one of
395 * `returned`, `failed` or `died`.
396 */
397 const returned: {
398 <Success>(op: ExternalSystem.Op<any, Success>, value: Success): StepOf<"Returned">;
399 <Success>(tag: string, op: ExternalSystem.Op<any, Success>, value: Success): StepOf<"Returned">;
400 } = (...a: ReadonlyArray<any>): StepOf<"Returned"> =>
401 outcome(a, (value) => ({ _tag: "Success", value }));
402
403 /** A real call to an external system that is not stubbed failed with this declared error. */
404 const failed: {
405 <Error>(op: ExternalSystem.Op<any, any, Error>, error: NoInfer<Error>): StepOf<"Returned">;
406 <Error>(
407 tag: string,
408 op: ExternalSystem.Op<any, any, Error>,
409 error: NoInfer<Error>,
410 ): StepOf<"Returned">;
411 } = (...a: ReadonlyArray<any>): StepOf<"Returned"> =>
412 outcome(a, (error) => ({ _tag: "Failure", error }));
413
414 /** A real call to an external system that is not stubbed died with a defect. */
415 const died: {
416 (op: ExternalSystem.Op): StepOf<"Returned">;
417 (tag: string, op: ExternalSystem.Op): StepOf<"Returned">;
418 } = (...a: ReadonlyArray<any>): StepOf<"Returned"> =>
419 typeof a[0] === "string"
420 ? { _tag: "Returned", tag: a[0], op: a[1], expected: { _tag: "Died" } }
421 : { _tag: "Returned", tag: undefined, op: a[0], expected: { _tag: "Died" } };
422
423 /** Move the clock: later commands are stamped with it, and scheduled commands now due fire. */
424 const clock = (at: string | number | DateTime.DateTime): StepOf<"Clock"> => ({ _tag: "Clock", at });
425
426 /** Move the clock forward by a duration, like `"1 day"`: the same as `clock` at the current time plus `by`. */
427 const advance = (by: Duration.Input): StepOf<"Advance"> => ({ _tag: "Advance", by });
428
429 type SagaClientOf<S> = S extends Context.Key<any, infer C> ? C : never;
430 type SagaKeyOf<S> =
431 SagaClientOf<S> extends Saga.Client<infer K, any, any, any> ? K | { readonly id: K } : never;
432 type SagaStatusOf<S> =
433 SagaClientOf<S> extends Saga.Client<any, any, infer A, infer E> ? Saga.Status<A, E> : never;
434
435 /** Complete a `DurableDeferred` a saga run waits on, then let it run. */
436 const signal = <S extends Saga.Any, Success extends Schema.Constraint>(
437 saga: S,
438 key: SagaKeyOf<S>,
439 deferred: DurableDeferred.DurableDeferred<Success, any>,
440 value: Success["Type"],
441 ): StepOf<"Signal"> => ({ _tag: "Signal", saga, key, deferred, value });
442
443 /**
444 * Check where a saga run is: running, completed with a result, rejected,
445 * interrupted, or died. `{ _tag: "Died" }` matches any defect; with a
446 * `defect`, it must read the same.
447 */
448 const saga = <S extends Saga.Any>(
449 saga: S,
450 key: SagaKeyOf<S>,
451 expected: SagaStatusOf<S> | { readonly _tag: "Died" },
452 ): StepOf<"Saga"> => ({
453 _tag: "Saga",
454 saga,
455 key,
456 expected: expected as Saga.Status<unknown, unknown>,
457 });
458
459 /** A saga status, in a form to compare: rejections encoded, defects as text. */
460 const statusJson = (status: Saga.Status<unknown, unknown> | { readonly _tag: "Died" }) =>
461 status._tag === "Rejected"
462 ? { _tag: "Rejected", rejection: encodeInstance(status.rejection as { readonly _tag: string }) }
463 : status._tag === "Died"
464 ? "defect" in status
465 ? { _tag: "Died", defect: String(status.defect) }
466 : { _tag: "Died" }
467 : status;
468
469 /**
470 * Provide a service to subsequent commands, as their middleware would (for
471 * example the current actor). Replaces any earlier value of the same service.
472 */
473 const provide = <I, S>(service: Context.Key<I, S>, value: S): ProvideStep<I> => ({
474 _tag: "Provide",
475 service: service as unknown as Context.Key<unknown, unknown>,
476 value,
477 });
478
479 const normalize = (value: unknown, redact = false): unknown => {
480 if (redact && Redacted.isRedacted(value)) return "<redacted>";
481 if (DateTime.isDateTime(value)) return DateTime.formatIso(value);
482 if (Array.isArray(value)) return value.map((v) => normalize(v, redact));
483 if (value !== null && typeof value === "object") {
484 const out: Record<string, unknown> = {};
485 for (const key of Object.keys(value)) out[key] = normalize((value as any)[key], redact);
486 return out;
487 }
488 return value;
489 };
490
491 /** JSON for a failure message: redacted values print as `<redacted>`. */
492 const show = (value: unknown) => JSON.stringify(normalize(value, true));
493
494 const clip = (text: string, max: number) =>
495 text.length > max ? `${text.slice(0, max - 1)}…` : text;
496
497 /** A short, one-line form of a value: `Tag { field: value }`, nested values elided. */
498 const brief = (value: unknown, depth = 0): string => {
499 if (Redacted.isRedacted(value)) return "<redacted>";
500 if (DateTime.isDateTime(value)) return DateTime.formatIso(value);
501 if (value instanceof Date) return value.toISOString();
502 if (typeof value === "string") return JSON.stringify(clip(value, 24));
503 if (typeof value === "bigint") return `${value}n`;
504 if (value === null || typeof value !== "object") return String(value);
505 if (Array.isArray(value))
506 return depth > 0 ? `[${value.length}]` : `[${value.map((v) => brief(v, 1)).join(", ")}]`;
507 const tag = typeof (value as any)._tag === "string" ? ((value as any)._tag as string) : undefined;
508 if (depth > 1) return tag ?? "{…}";
509 const fields = Object.keys(value)
510 .filter((key) => key !== "_tag")
511 .map((key) => `${key}: ${brief((value as any)[key], depth + 1)}`);
512 const body = fields.length > 0 ? `{ ${fields.join(", ")} }` : tag ? "" : "{}";
513 return tag && body ? `${tag} ${body}` : (tag ?? body);
514 };
515
516 const summarize = (value: unknown) => clip(brief(value), 80);
517 const summarizeAll = (values: ReadonlyArray<unknown>, none = "nothing new") =>
518 values.length === 0 ? none : clip(values.map((v) => brief(v)).join(", "), 80);
519
520 const refName = (ref: Aggregate.Ref) => `${ref.aggregate}/${ref.id}`;
521 const callName = (tag: string | undefined, op: ExternalSystem.Op) =>
522 `${tag === undefined ? "" : `"${tag}" `}${op.system}.${op.op}`;
523
524 /** A `clock` step's time in epoch milliseconds; `NaN` for a string that is not a time. */
525 const clockMillis = (at: string | number | DateTime.DateTime) =>
526 typeof at === "number"
527 ? at
528 : typeof at === "string"
529 ? Date.parse(at)
530 : DateTime.toEpochMillis(at);
531
532 /** An `advance` step's duration; `undefined` for an input that is not a finite duration. */
533 const advanceDuration = (by: Duration.Input) =>
534 Option.getOrUndefined(Option.filter(Duration.fromInput(by), Duration.isFinite));
535
536 const showDurationInput = (by: Duration.Input): string =>
537 typeof by === "string" ? by : Formatter.format(by);
538
539 /** A one-line summary of a step, before it runs. */
540 const describeStep = (s: Step): string => {
541 switch (s._tag) {
542 case "Advance": {
543 const by = advanceDuration(s.by);
544 if (by === undefined) return showDurationInput(s.by);
545 return `${Duration.isNegative(by) ? "" : "+"}${Duration.format(by)}`;
546 }
547 case "Clock": {
548 const at = clockMillis(s.at);
549 return Number.isNaN(at) ? String(s.at) : new Date(at).toISOString();
550 }
551 case "Provide":
552 return `${s.service.key} = ${summarize(s.value)}`;
553 case "Given":
554 case "Then":
555 return `${refName(s.ref)}: ${summarizeAll(s.events)}`;
556 case "When":
557 return `${refName(s.ref)}: ${summarize(s.command)}`;
558 case "Rejected":
559 return summarize(s.rejection);
560 case "Replied":
561 return summarize(s.reply);
562 case "State":
563 return `${refName(s.ref)}${typeof s.expected === "function" ? "" : `: ${summarize(s.expected)}`}`;
564 case "View":
565 return `${s.view.viewName}(${Aggregate.targetId(s.key)})${s.expected === none ? ": none" : typeof s.expected === "function" ? "" : `: ${summarize(s.expected)}`}`;
566 case "Emitted":
567 return `${s.view.viewName}(${Aggregate.targetId(s.key)})${typeof s.expected === "function" ? "" : `: ${summarizeAll(s.expected as ReadonlyArray<unknown>)}`}`;
568 case "Streamed":
569 return `${s.stream.streamName}/${Aggregate.targetId(s.key)}: ${summarizeAll(s.events)}`;
570 case "Call":
571 return `${callName(s.tag, s.op)} ${summarize(s.args)}`;
572 case "Answer":
573 return `${callName(s.tag, s.op)} → ${
574 Exit.isSuccess(s.exit)
575 ? summarize(s.exit.value)
576 : Option.match(Cause.findErrorOption(s.exit.cause), {
577 onSome: (error) => `fail ${summarize(error)}`,
578 onNone: () => "die",
579 })
580 }`;
581 case "Returned":
582 return `${callName(s.tag, s.op)} → ${
583 s.expected._tag === "Success"
584 ? summarize(s.expected.value)
585 : s.expected._tag === "Failure"
586 ? `failed ${summarize(s.expected.error)}`
587 : "died"
588 }`;
589 case "Signal":
590 return `${s.saga.sagaName} ${summarize(s.key)}: ${summarize(s.value)}`;
591 case "Saga":
592 return `${s.saga.sagaName} ${summarize(s.key)}: ${s.expected._tag}`;
593 }
594 };
595
596 /** The story, step by step, with the failed step marked: the tail of a failure message. */
597 const renderReport = (
598 failure: StepFailed,
599 steps: ReadonlyArray<StepReport>,
600 events: Readonly<Record<string, ReadonlyArray<string>>>,
601 ): string => {
602 const width = String(steps.length).length;
603 const lines: Array<string> = [];
604 for (const s of steps) {
605 const mark = s.status === "passed" ? "✓" : s.status === "failed" ? "✗" : " ";
606 const head = ` ${mark} ${String(s.step).padStart(width)} ${s.kind.padEnd(10)} `;
607 const indent = " ".repeat(head.length);
608 if (s.status !== "failed") {
609 lines.push(head + s.summary);
610 continue;
611 }
612 if (failure.expected !== undefined && failure.actual !== undefined) {
613 // `Ref: expected X` / ` got Y`, with the ref (if any) kept in front.
614 const label = failure.label === undefined ? "" : `${failure.label}: `;
615 lines.push(`${head}${label}expected ${failure.expected}`);
616 lines.push(`${indent}${" ".repeat(label.length)}got ${failure.actual}`);
617 } else {
618 lines.push(head + s.summary);
619 }
620 if (failure.detail !== undefined) lines.push(indent + failure.detail);
621 }
622 if (failure.atEnd) {
623 const head = ` ✗ ${" ".repeat(width)} ${"end".padEnd(10)} `;
624 const detail = failure.detail?.split("\n") ?? [];
625 lines.push(detail.length > 0 ? head + detail[0] : head.trimEnd());
626 for (const line of detail.slice(1)) lines.push(" ".repeat(head.length) + line);
627 }
628 lines.push(" events so far");
629 const streams = Object.entries(events);
630 if (streams.length === 0) lines.push(" nothing");
631 for (const [stream, tags] of streams)
632 lines.push(` ${stream}: ${tags.length === 0 ? "nothing" : clip(tags.join(" → "), 120)}`);
633 return lines.join("\n");
634 };
635
636 const encodeInstance = (value: { readonly _tag: string }): unknown => {
637 const schema = (value as any).constructor as Schema.Top;
638 // oxlint-disable-next-line effecttsgo/schema-sync -- encodes a value for a sync story report
639 return Schema.encodeUnknownSync(Schema.toCodecJson(schema as any) as any)(value);
640 };
641
642 const equal = (a: unknown, b: unknown) => show(a) === show(b);
643
644 /** A tagged error by its encoded fields; anything else as it is. */
645 const errorJson = (error: unknown): unknown => {
646 if (error !== null && typeof error === "object" && "_tag" in error) {
647 try {
648 return encodeInstance(error as { readonly _tag: string });
649 } catch {
650 return normalize(error);
651 }
652 }
653 return normalize(error);
654 };
655
656 const exitJson = (
657 exit: Exit.Exit<unknown, unknown>,
658 ):
659 | { readonly _tag: "Success"; readonly value: unknown }
660 | { readonly _tag: "Failure"; readonly error: unknown }
661 | { readonly _tag: "Died"; readonly defect: string } => {
662 if (Exit.isSuccess(exit)) return { _tag: "Success", value: normalize(exit.value) };
663 const error = Cause.findErrorOption(exit.cause);
664 return Option.isSome(error)
665 ? { _tag: "Failure", error: errorJson(error.value) }
666 : { _tag: "Died", defect: String(Cause.squash(exit.cause)) };
667 };
668
669 const partial = (expected: unknown, actual: unknown): boolean => {
670 const e = normalize(expected);
671 const a = normalize(actual);
672 if (e !== null && typeof e === "object" && !Array.isArray(e)) {
673 if (a === null || typeof a !== "object") return false;
674 return Object.keys(e).every((k) => partial((e as any)[k], (a as any)[k]));
675 }
676 return JSON.stringify(e) === JSON.stringify(a);
677 };
678
679 interface PendingCall {
680 readonly system: string;
681 readonly op: string;
682 readonly args: unknown;
683 readonly deferred: Deferred.Deferred<unknown, unknown>;
684 /** The name its `call` step gave it, if any. */
685 tag: string | undefined;
686 /** Whether a `call` step checked its arguments. */
687 expected: boolean;
688 }
689
690 interface ObservedCall {
691 readonly system: string;
692 readonly op: string;
693 readonly args: unknown;
694 /** How the call ended; undefined while it runs. */
695 exit: Exit.Exit<unknown, unknown> | undefined;
696 readonly done: Deferred.Deferred<void>;
697 /** The name its `call` step gave it, if any. */
698 tag: string | undefined;
699 /** Whether a `call` step matched it. */
700 expected: boolean;
701 }
702
703 /** Options for {@link make}. */
704 interface StoryOptions<Policies, LE, LR, Systems> {
705 /** The policies' and projections' Layers. Required when the model has either. */
706 readonly layer?: Layer.Layer<Policies, LE, LR>;
707 /**
708 * External systems to fake. Each call to one waits until the story answers it
709 * with `succeed`, `fail` or `die`. Systems not listed are called for real,
710 * through the Layers you provide to the story, and the story asserts what
711 * each call returned with `returned`, `failed` or `died`.
712 */
713 readonly stub?: ReadonlyArray<Systems>;
714 }
715
716 /**
717 * Create a story runner for a Domain. A story is a sequence of steps run
718 * against an in-memory host: policies run for real, calls to stubbed external
719 * systems suspend until the story answers them, and calls to the others run
720 * through the Layers you provide while the story records them.
721 *
722 * **Example:** A story
723 * ```typescript
724 * const story = Story.make(Bank, {
725 * layer: BankPolicies,
726 * stub: [FraudCheck, Payments],
727 * });
728 *
729 * it.effect("withdraw replies with the new balance", () =>
730 * story(
731 * Story.given(a1, new AccountOpened({ ... }), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
732 * Story.provide(CurrentActor, sam),
733 * Story.when(a1, new WithdrawMoney({ amount: 30 })),
734 * Story.then(a1, new MoneyWithdrawn({ amount: 30, balanceAfter: 70 })),
735 * Story.replied({ balance: 70 }),
736 * ),
737 * );
738 * ```
739 */
740 const make =
741 <
742 Name extends string,
743 Provided,
744 Policies,
745 LE = never,
746 LR = never,
747 Systems extends ExternalSystem.Any = never,
748 >(
749 domain: Model.ModelClass<Name, Provided, Policies>,
750 ...[options = {}]: [Policies] extends [never]
751 ? [options?: StoryOptions<Policies, LE, LR, Systems>]
752 : [options: StoryOptions<Policies, LE, LR, Systems> & { readonly layer: unknown }]
753 ) =>
754 <const S extends ReadonlyArray<Step>>(
755 ...steps: S & Checked<S>
756 ): Effect.Effect<
757 void,
758 StoryFailure | LE,
759 Exclude<LR, Provided | ExternalSystem.Identifier<Systems> | WorkflowEngine.WorkflowEngine>
760 > =>
761 Effect.gen(function* () {
762 const clockState = { now: Date.parse("2026-01-01T00:00:00.000Z") };
763 const platform = InMemory.make({ manual: true, now: () => clockState.now });
764 const calls: Array<PendingCall> = [];
765 const observed: Array<ObservedCall> = [];
766 const stubbed = new Set((options.stub ?? []).map((system) => system.systemName));
767 const recorder: ExternalSystem.CallRecorder = {
768 record: (system, op, args, call) =>
769 Effect.gen(function* () {
770 const entry: ObservedCall = {
771 system,
772 op,
773 args,
774 exit: undefined,
775 done: yield* Deferred.make<void>(),
776 tag: undefined,
777 expected: false,
778 };
779 observed.push(entry);
780 return yield* call.pipe(
781 Effect.onExit((exit) =>
782 Effect.suspend(() => {
783 entry.exit = exit;
784 return Deferred.succeed(entry.done, undefined);
785 }),
786 ),
787 );
788 }),
789 };
790 const systemLayers = (options.stub ?? []).map((system) =>
791 Layer.effect(
792 system as Context.Key<unknown, unknown>,
793 Effect.map(
794 ExternalSystem.compileChecks(system.systemName, system.ops),
795 (checks) =>
796 ExternalSystem.observeOps(
797 system.systemName,
798 // The story's answers are checked like an adapter's.
799 ExternalSystem.validateOps(
800 checks,
801 Object.fromEntries(
802 Object.keys(system.ops).map((op) => [
803 op,
804 (args: unknown) =>
805 platform.control.suspended(
806 Effect.gen(function* () {
807 const deferred = yield* Deferred.make<unknown, unknown>();
808 calls.push({
809 system: system.systemName,
810 op,
811 args,
812 deferred,
813 tag: undefined,
814 expected: false,
815 });
816 return yield* Deferred.await(deferred);
817 }),
818 ),
819 ]),
820 ),
821 ),
822 ) as never,
823 ),
824 ),
825 );
826 const systems = Layer.mergeAll(Layer.empty, ...systemLayers);
827 const policies = (
828 options.layer ?? (Layer.empty as unknown as Layer.Layer<Policies, LE, LR>)
829 ).pipe(Layer.provide(systems));
830 const hosted = domain
831 .layer(policies)
832 .pipe(Layer.provide(Layer.mergeAll(platform.layer, systems)));
833
834 // The aggregates the story touched, for the report's "events so far".
835 const touched = new Map<string, Aggregate.Ref>();
836
837 const run = Effect.gen(function* () {
838 const internals = yield* Model.Internals;
839 const cursors = new Map<string, number>();
840 // The step that committed each event, by `Aggregate/id#index`.
841 const committedAt = new Map<string, number>();
842 const attribute = (step: number) => {
843 for (const { aggregate, id, index } of platform.control.commits.slice(committedAt.size))
844 committedAt.set(`${aggregate}/${id}#${index}`, step);
845 };
846 let last:
847 | { readonly _tag: "Accepted"; readonly receipt: Aggregate.Receipt }
848 | { readonly _tag: "Rejected"; readonly rejection: { readonly _tag: string } }
849 | undefined;
850 let unassertedRejection:
851 | { readonly step: number; readonly rejection: { readonly _tag: string } }
852 | undefined;
853 let provided = Context.empty() as Context.Context<unknown>;
854 const assertedDeaths = new Set<string>();
855
856 const storeOf = (ref: Aggregate.Ref) => internals.aggregates.get(ref.aggregate)!;
857 const committed = (ref: Aggregate.Ref) =>
858 storeOf(ref).events?.(ref.id as string) ?? Effect.succeed([]);
859
860 const settle = (step: number) =>
861 Effect.gen(function* () {
862 for (let i = 0; i < 10_000; i++) {
863 // Real calls take real time: wait for them instead of spinning.
864 for (const call of observed) {
865 if (call.exit === undefined) yield* Deferred.await(call.done);
866 }
867 yield* platform.control.drain;
868 yield* Effect.yieldNow;
869 if (yield* platform.control.idle) {
870 yield* Effect.yieldNow;
871 yield* platform.control.drain;
872 if (yield* platform.control.idle) {
873 if (platform.control.failures.length > 0) {
874 return yield* new StepFailed({
875 step,
876 message: `a policy or projection failed: ${String(platform.control.failures[0])}`,
877 });
878 }
879 return;
880 }
881 }
882 }
883 return yield* new StepFailed({
884 step,
885 message: "the domain did not settle (a policy or projection is looping?)",
886 });
887 });
888
889 const rejectionNotAsserted = (rejected: NonNullable<typeof unassertedRejection>) =>
890 new StepFailed({
891 step: rejected.step,
892 message: `the command was rejected with ${rejected.rejection._tag}, which no step asserts`,
893 detail: `rejected ${summarize(rejected.rejection)}`,
894 });
895
896 for (const [index, s] of steps.entries()) {
897 const step = index + 1;
898 attribute(index);
899 const fail = (
900 message: string,
901 compared?: {
902 readonly expected: string;
903 readonly actual: string;
904 readonly label?: string;
905 },
906 ) => new StepFailed({ step, message: `${s._tag}: ${message}`, ...compared });
907 if (unassertedRejection && s._tag !== "Rejected") {
908 return yield* rejectionNotAsserted(unassertedRejection);
909 }
910 if ("ref" in s) touched.set(refName(s.ref), s.ref);
911 switch (s._tag) {
912 case "Clock": {
913 const at = clockMillis(s.at);
914 if (Number.isNaN(at)) return yield* fail(`${String(s.at)} is not a time`);
915 // Once a step has run at the current time, the clock only moves forward.
916 const started = steps.slice(0, index).some((earlier) => earlier._tag !== "Provide");
917 if (started && at < clockState.now) {
918 const now = new Date(clockState.now).toISOString();
919 return yield* fail(
920 `the clock cannot move back, from ${now} to ${new Date(at).toISOString()}`,
921 { expected: `${now} or later`, actual: new Date(at).toISOString() },
922 );
923 }
924 clockState.now = at;
925 // Scheduled commands that are now due fire, and their policies run.
926 yield* settle(step);
927 break;
928 }
929 case "Advance": {
930 const by = advanceDuration(s.by);
931 if (by === undefined)
932 return yield* fail(`${showDurationInput(s.by)} is not a duration`);
933 if (Duration.isNegative(by)) {
934 return yield* fail(`the clock only moves forward, not by ${Duration.format(by)}`);
935 }
936 clockState.now += Duration.toMillis(by);
937 yield* settle(step);
938 break;
939 }
940 case "Provide": {
941 provided = Context.add(provided, s.service, s.value);
942 break;
943 }
944 case "Given": {
945 const store = storeOf(s.ref);
946 if (!store.seed) return yield* fail("the platform cannot seed events");
947 yield* store.seed(
948 s.ref.id as string,
949 yield* Effect.forEach(s.events, internals.kernel.encodeEvent),
950 );
951 cursors.set(`${s.ref.aggregate}/${s.ref.id}`, (yield* committed(s.ref)).length);
952 yield* settle(step);
953 break;
954 }
955 case "When": {
956 const client = yield* Aggregate.refClass(s.ref) as unknown as Context.Key<
957 never,
958 Aggregate.ClientImpl
959 >;
960 const result = yield* client
961 .send(s.ref, s.command, { commandId: s.commandId ?? `story:${step}` })
962 .pipe(Effect.provide(provided), Effect.result);
963 if (result._tag === "Success") {
964 last = { _tag: "Accepted", receipt: result.success };
965 } else {
966 last = { _tag: "Rejected", rejection: result.failure as { readonly _tag: string } };
967 unassertedRejection = { step, rejection: last.rejection };
968 }
969 yield* settle(step);
970 break;
971 }
972 case "Then": {
973 const stream = `${s.ref.aggregate}/${s.ref.id}`;
974 const events = yield* committed(s.ref);
975 const from = cursors.get(stream) ?? 0;
976 const actual = events
977 .slice(from, from + Math.max(s.events.length, 1))
978 .map((e) => e.event);
979 const expected = s.events.map(encodeInstance);
980 // Decoded, so redacted fields stay redacted in the message.
981 const got = yield* Effect.forEach(events.slice(from), (e) =>
982 internals.kernel.decodeEvent(e.event),
983 );
984 const compared = {
985 label: stream,
986 expected: summarizeAll(s.events),
987 actual: summarizeAll(got),
988 };
989 if (s.events.length === 0) {
990 if (events.length > from) {
991 return yield* fail(
992 `expected no new events on ${stream}, got ${show(got)}`,
993 compared,
994 );
995 }
996 break;
997 }
998 if (!equal(actual.slice(0, expected.length), expected)) {
999 return yield* fail(
1000 `on ${stream}\n expected ${show(s.events)}\n actual ${show(got)}`,
1001 compared,
1002 );
1003 }
1004 cursors.set(stream, from + expected.length);
1005 break;
1006 }
1007 case "Rejected": {
1008 if (last?._tag !== "Rejected")
1009 return yield* fail(
1010 `expected a rejection, the command was ${last ? "accepted" : "never sent"}`,
1011 {
1012 expected: summarize(s.rejection),
1013 actual: last ? `accepted ${summarize(last.receipt.reply)}` : "never sent",
1014 },
1015 );
1016 const expected = encodeInstance(s.rejection);
1017 const actual = encodeInstance(last.rejection);
1018 if (!equal(expected, actual))
1019 return yield* fail(`expected ${show(s.rejection)}, got ${show(last.rejection)}`, {
1020 expected: summarize(s.rejection),
1021 actual: summarize(last.rejection),
1022 });
1023 unassertedRejection = undefined;
1024 break;
1025 }
1026 case "Replied": {
1027 if (last?._tag !== "Accepted")
1028 return yield* fail("the last command was not accepted");
1029 if (!equal(last.receipt.reply, s.reply)) {
1030 return yield* fail(`expected ${show(s.reply)}, got ${show(last.receipt.reply)}`, {
1031 expected: summarize(s.reply),
1032 actual: summarize(last.receipt.reply),
1033 });
1034 }
1035 break;
1036 }
1037 case "State": {
1038 const client = yield* Aggregate.refClass(s.ref) as unknown as Context.Key<
1039 never,
1040 Aggregate.ClientImpl
1041 >;
1042 const current = yield* client.state(s.ref);
1043 if (typeof s.expected === "function") {
1044 const assert = s.expected as (state: unknown) => void;
1045 yield* Effect.try({ try: () => assert(current), catch: (e) => fail(String(e)) });
1046 } else if (!partial(s.expected, current)) {
1047 const label = refName(s.ref);
1048 return yield* fail(
1049 `${label}\n expected ${show(s.expected)}\n actual ${show(current)}`,
1050 { label, expected: summarize(s.expected), actual: summarize(current) },
1051 );
1052 }
1053 break;
1054 }
1055 case "View": {
1056 const host = yield* s.view as unknown as Context.Key<
1057 never,
1058 View.Host<unknown, Key.Any, unknown>
1059 >;
1060 const current = yield* host.query(s.key).pipe(Effect.orDie);
1061 if (s.expected === none) {
1062 if (Option.isSome(current))
1063 return yield* fail(
1064 `expected ${s.view.viewName}(${Aggregate.targetId(s.key)}) to not exist, got ${show(current.value)}`,
1065 {
1066 label: `${s.view.viewName}(${Aggregate.targetId(s.key)})`,
1067 expected: "none",
1068 actual: summarize(current.value),
1069 },
1070 );
1071 break;
1072 }
1073 const viewLabel = `${s.view.viewName}(${Aggregate.targetId(s.key)})`;
1074 if (Option.isNone(current))
1075 return yield* fail(`${viewLabel} does not exist`, {
1076 label: viewLabel,
1077 expected: typeof s.expected === "function" ? "a state" : summarize(s.expected),
1078 actual: "none",
1079 });
1080 if (typeof s.expected === "function") {
1081 const assert = s.expected as (state: unknown) => void;
1082 yield* Effect.try({
1083 try: () => assert(current.value),
1084 catch: (e) => fail(String(e)),
1085 });
1086 } else if (!partial(s.expected, current.value)) {
1087 return yield* fail(
1088 `${viewLabel}\n expected ${show(s.expected)}\n actual ${show(current.value)}`,
1089 {
1090 label: viewLabel,
1091 expected: summarize(s.expected),
1092 actual: summarize(current.value),
1093 },
1094 );
1095 }
1096 break;
1097 }
1098 case "Emitted": {
1099 const host = yield* s.view as unknown as Context.Key<
1100 never,
1101 View.Host<unknown, Key.Any, unknown>
1102 >;
1103 const { entries } = yield* host.list(s.key);
1104 if (typeof s.expected === "function") {
1105 const assert = s.expected as (entries: ReadonlyArray<unknown>) => void;
1106 yield* Effect.try({ try: () => assert(entries), catch: (e) => fail(String(e)) });
1107 } else {
1108 const expected = s.expected as ReadonlyArray<unknown>;
1109 const events = entries.map((entry) => entry.event);
1110 const ok =
1111 expected.length === events.length &&
1112 expected.every((e, i) => partial(e, events[i]));
1113 if (!ok)
1114 return yield* fail(
1115 `${s.view.viewName}(${Aggregate.targetId(s.key)})\n expected ${show(expected)}\n actual ${show(events)}`,
1116 );
1117 }
1118 break;
1119 }
1120 case "Streamed": {
1121 const store = internals.streams.get(s.stream.streamName)!;
1122 const key = Aggregate.targetId(s.key);
1123 const id = `${s.stream.streamName}/${key}`;
1124 const entries = yield* store.list(key);
1125 const from = cursors.get(id) ?? 0;
1126 const actual = entries.slice(from).map((e) => e.event);
1127 const expected = s.events.map(encodeInstance);
1128 if (s.events.length === 0) {
1129 if (actual.length > 0)
1130 return yield* fail(`expected nothing new on ${id}, got ${show(actual)}`);
1131 break;
1132 }
1133 if (!equal(actual.slice(0, expected.length), expected)) {
1134 return yield* fail(
1135 `on ${id}\n expected ${show(expected)}\n actual ${show(actual)}`,
1136 );
1137 }
1138 cursors.set(id, from + expected.length);
1139 break;
1140 }
1141 case "Call": {
1142 const name = `${s.op.system}.${s.op.op}`;
1143 if (s.tag !== undefined && observed.some((c) => c.tag === s.tag)) {
1144 return yield* fail(`"${s.tag}" already names a call`);
1145 }
1146 if (!stubbed.has(s.op.system)) {
1147 const made = observed.filter((c) => c.system === s.op.system && c.op === s.op.op);
1148 // Each real call is matched once, in the order calls were made.
1149 const match = made.find((c) => !c.expected && partial(s.args, c.args));
1150 if (!match) {
1151 return yield* fail(
1152 `no unmatched call to ${name} matches ${show(s.args)}; made: ${show(made.map((c) => c.args))}`,
1153 );
1154 }
1155 match.expected = true;
1156 match.tag = s.tag;
1157 break;
1158 }
1159 const pending = calls.filter((c) => c.system === s.op.system && c.op === s.op.op);
1160 // Calls are kept in the order they were made: each is matched once, earliest first.
1161 const match = pending.find((c) => !c.expected && partial(s.args, c.args));
1162 if (!match) {
1163 return yield* fail(
1164 `no unmatched pending call to ${name} matches ${show(s.args)}; pending: ${show(pending.map((c) => c.args))}`,
1165 );
1166 }
1167 if (s.tag !== undefined) {
1168 if (calls.some((c) => c.tag === s.tag)) {
1169 return yield* fail(`"${s.tag}" already names a pending call`);
1170 }
1171 match.tag = s.tag;
1172 }
1173 match.expected = true;
1174 break;
1175 }
1176 case "Signal": {
1177 const client = yield* s.saga as unknown as Context.Key<
1178 never,
1179 Saga.Client<unknown, unknown, unknown, unknown>
1180 >;
1181 yield* client.get(s.key).signal(s.deferred as never, s.value);
1182 yield* settle(step);
1183 break;
1184 }
1185 case "Saga": {
1186 const client = yield* s.saga as unknown as Context.Key<
1187 never,
1188 Saga.Client<unknown, unknown, unknown, unknown>
1189 >;
1190 const run = client.get(s.key);
1191 const actual = yield* run.status;
1192 // `{ _tag: "Died" }` matches any defect.
1193 const compared =
1194 actual._tag === "Died" && !("defect" in s.expected)
1195 ? { _tag: "Died" as const }
1196 : actual;
1197 if (!equal(statusJson(compared), statusJson(s.expected))) {
1198 return yield* fail(
1199 `${s.saga.sagaName}\n expected ${show(statusJson(s.expected))}\n actual ${show(statusJson(actual))}`,
1200 );
1201 }
1202 if (actual._tag === "Died")
1203 // The engine names a model's sagas `<model>/<saga>`.
1204 assertedDeaths.add(`${domain.modelName}/${s.saga.sagaName}/${run.executionId}`);
1205 break;
1206 }
1207 case "Answer": {
1208 const name = `${s.op.system}.${s.op.op}`;
1209 if (!stubbed.has(s.op.system)) {
1210 return yield* fail(
1211 `${s.op.system} is not stubbed, so its calls run for real; assert how one ended with returned, failed or died`,
1212 );
1213 }
1214 let call: PendingCall | undefined;
1215 if (s.tag !== undefined) {
1216 call = calls.find((c) => c.tag === s.tag);
1217 if (!call) {
1218 const tags = calls.flatMap((c) => (c.tag === undefined ? [] : [`"${c.tag}"`]));
1219 return yield* fail(
1220 `no pending call is named "${s.tag}"; named: ${tags.length > 0 ? tags.join(", ") : "none"}`,
1221 );
1222 }
1223 if (call.system !== s.op.system || call.op !== s.op.op) {
1224 return yield* fail(
1225 `"${s.tag}" names a call to ${call.system}.${call.op}, not ${name}`,
1226 );
1227 }
1228 } else {
1229 const pending = calls.filter((c) => c.system === s.op.system && c.op === s.op.op);
1230 if (pending.length === 0) return yield* fail(`no pending call to ${name}`);
1231 if (pending.length > 1) {
1232 return yield* fail(
1233 `${pending.length} pending calls to ${name}; name each with call("<tag>", ...) and answer it by tag`,
1234 );
1235 }
1236 call = pending[0];
1237 }
1238 if (!call!.expected) {
1239 return yield* fail(
1240 `${name}(${show(call!.args)}) is answered before a call step checks its arguments`,
1241 );
1242 }
1243 calls.splice(calls.indexOf(call!), 1);
1244 yield* Deferred.done(call!.deferred, s.exit);
1245 yield* settle(step);
1246 break;
1247 }
1248 case "Returned": {
1249 const name = `${s.op.system}.${s.op.op}`;
1250 if (stubbed.has(s.op.system)) {
1251 return yield* fail(
1252 `${s.op.system} is stubbed; answer its calls with succeed, fail or die`,
1253 );
1254 }
1255 let call: ObservedCall | undefined;
1256 if (s.tag !== undefined) {
1257 call = observed.find((c) => c.tag === s.tag);
1258 if (!call) return yield* fail(`no call is named "${s.tag}"`);
1259 if (call.system !== s.op.system || call.op !== s.op.op) {
1260 return yield* fail(
1261 `"${s.tag}" names a call to ${call.system}.${call.op}, not ${name}`,
1262 );
1263 }
1264 } else {
1265 const made = observed.filter((c) => c.system === s.op.system && c.op === s.op.op);
1266 if (made.length === 0) return yield* fail(`no unasserted call to ${name}`);
1267 if (made.length > 1) {
1268 return yield* fail(
1269 `${made.length} unasserted calls to ${name}; name each with call("<tag>", ...) and assert it by tag`,
1270 );
1271 }
1272 call = made[0]!;
1273 }
1274 if (!call.expected) {
1275 return yield* fail(
1276 `${name}(${show(call.args)}) is asserted before a call step checks its arguments`,
1277 );
1278 }
1279 const actual = exitJson(call.exit!);
1280 const expected =
1281 s.expected._tag === "Success"
1282 ? { _tag: "Success", value: normalize(s.expected.value) }
1283 : s.expected._tag === "Failure"
1284 ? { _tag: "Failure", error: errorJson(s.expected.error) }
1285 : { _tag: "Died" };
1286 const compared = actual._tag === "Died" ? { _tag: "Died" } : actual;
1287 if (!equal(expected, compared)) {
1288 return yield* fail(
1289 `${name}(${show(call.args)})\n expected ${show(expected)}\n actual ${show(actual)}`,
1290 );
1291 }
1292 observed.splice(observed.indexOf(call), 1);
1293 break;
1294 }
1295 }
1296 }
1297 if (unassertedRejection) return yield* rejectionNotAsserted(unassertedRejection);
1298 const death = platform.control.deaths.find(
1299 ({ saga, executionId }) => !assertedDeaths.has(`${saga}/${executionId}`),
1300 );
1301 if (death) {
1302 return yield* new StepFailed({
1303 step: steps.length,
1304 atEnd: true,
1305 message: `saga ${death.saga.slice(`${domain.modelName}/`.length)} run ${death.executionId} died with ${String(death.defect)}, which no step asserts`,
1306 });
1307 }
1308 if (observed.length > 0) {
1309 return yield* new StepFailed({
1310 step: steps.length,
1311 atEnd: true,
1312 message: `real external system calls no step asserts (use returned, failed or died): ${show(observed.map((c) => `${c.system}.${c.op}(${show(c.args)})`))}`,
1313 });
1314 }
1315 if (calls.length > 0) {
1316 return yield* new StepFailed({
1317 step: steps.length,
1318 atEnd: true,
1319 message: `unanswered external system calls at the end of the story: ${show(calls.map((c) => `${c.system}.${c.op}(${show(c.args)})`))}`,
1320 });
1321 }
1322 attribute(steps.length);
1323 // Every committed event past its stream's cursor is one no `then` asserts.
1324 const unasserted: Array<string> = [];
1325 const streams = new Map<string, Aggregate.Ref>();
1326 for (const { aggregate, id } of platform.control.commits)
1327 streams.set(`${aggregate}/${id}`, { aggregate, id } as Aggregate.Ref);
1328 for (const [stream, ref] of streams) {
1329 const events = yield* committed(ref);
1330 const from = cursors.get(stream) ?? 0;
1331 if (events.length <= from) continue;
1332 touched.set(stream, ref);
1333 // Decoded, so redacted fields stay redacted in the message.
1334 const rest = yield* Effect.forEach(events.slice(from), (e) =>
1335 internals.kernel.decodeEvent(e.event),
1336 );
1337 const first = committedAt.get(`${stream}#${from}`);
1338 unasserted.push(
1339 `${stream}: ${summarizeAll(rest)}${first === undefined ? "" : ` (from step ${first})`}`,
1340 );
1341 }
1342 if (unasserted.length > 0) {
1343 return yield* new StepFailed({
1344 step: steps.length,
1345 atEnd: true,
1346 message: `committed events no step asserts (assert them with then): ${unasserted.join("; ")}`,
1347 detail: unasserted.join("\n"),
1348 });
1349 }
1350 });
1351
1352 // Turn a failed step into a failure that shows the whole story.
1353 const report = (failure: StepFailed) =>
1354 Effect.gen(function* () {
1355 const internals = yield* Model.Internals;
1356 const events: Record<string, ReadonlyArray<string>> = {};
1357 for (const [name, ref] of touched) {
1358 const committed =
1359 internals.aggregates.get(ref.aggregate)!.events?.(ref.id as string) ??
1360 Effect.succeed([]);
1361 events[name] = (yield* committed).map(
1362 (e) => (e.event as { readonly _tag: string })._tag,
1363 );
1364 }
1365 const reports = steps.map((s, index): StepReport => ({
1366 step: index + 1,
1367 kind: s._tag,
1368 status:
1369 index + 1 < failure.step || (failure.atEnd && index + 1 === failure.step)
1370 ? "passed"
1371 : index + 1 === failure.step
1372 ? "failed"
1373 : "not-run",
1374 summary: describeStep(s),
1375 }));
1376 return yield* new StoryFailure({
1377 step: failure.step,
1378 reason: failure.message,
1379 message: `${failure.message}\n\n${renderReport(failure, reports, events)}`,
1380 steps: reports,
1381 events,
1382 });
1383 });
1384
1385 // `hosted` satisfies the Domain, the platform and the stubbed external systems; what
1386 // remains is whatever the policy Layers need from outside (`LR`'s rest).
1387 return yield* run.pipe(
1388 Effect.catchTag("StepFailed", report),
1389 Effect.provide(
1390 Layer.mergeAll(hosted, Layer.succeed(ExternalSystem.CallRecorder, recorder)),
1391 ),
1392 );
1393 }) as Effect.Effect<
1394 void,
1395 StoryFailure | LE,
1396 Exclude<LR, Provided | ExternalSystem.Identifier<Systems> | WorkflowEngine.WorkflowEngine>
1397 >;
1398
1399 /**
1400 * Given / when / then specifications of a domain model, run against the real
1401 * model in memory: policies run for real, calls to stubbed external systems
1402 * wait until you answer them, calls to the others run through their adapters
1403 * while the story records them, and a clock you control stamps commands and
1404 * fires scheduled ones. A story fails on any committed event, rejection,
1405 * external system call or saga defect it doesn't account for.
1406 *
1407 * ### Writing a story
1408 * **Example:** A withdrawal and an overdraft
1409 * ```typescript
1410 * import { it } from "@effect/vitest";
1411 * import { Story } from "@alchemy.run/domain/Story";
1412 * import { Account, InsufficientFunds, MoneyDeposited, MoneyWithdrawn, WithdrawMoney } from "../src/Account.ts";
1413 * import { Bank, BankPolicies } from "../src/Bank.ts";
1414 *
1415 * const story = Story.make(Bank, { layer: BankPolicies });
1416 * const account = Account.ref("a-1");
1417 *
1418 * it.effect("withdraws within the balance, and refuses beyond it", () =>
1419 * story(
1420 * Story.given(account, new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
1421 * Story.when(account, new WithdrawMoney({ amount: 30 })),
1422 * Story.then(account, new MoneyWithdrawn({ amount: 30, balanceAfter: 70 })),
1423 * Story.replied({ balance: 70 }),
1424 * Story.when(account, new WithdrawMoney({ amount: 100 })),
1425 * Story.rejected(new InsufficientFunds({ balance: 70, requested: 100 })),
1426 * ),
1427 * );
1428 * ```
1429 *
1430 * ### External systems and the clock
1431 * **Example:** Answer an external system call, then move the clock
1432 * ```typescript
1433 * Story.call(FraudCheck.score, { accountId: account.id, amount: 60_000 }),
1434 * Story.succeed(FraudCheck.score, { risk: 0.95 }),
1435 * Story.clock("2026-01-02T09:00:00Z"),
1436 * Story.advance("1 day"),
1437 * ```
1438 *
1439 * **Example:** Name calls when several are waiting
1440 * ```typescript
1441 * Story.call("a-1", FraudCheck.score, { accountId: a1.id }),
1442 * Story.call("a-2", FraudCheck.score, { accountId: a2.id }),
1443 * Story.succeed("a-2", FraudCheck.score, { risk: 0.1 }),
1444 * Story.succeed("a-1", FraudCheck.score, { risk: 0.95 }),
1445 * ```
1446 *
1447 * **Example:** Assert a real call to a system that is not stubbed
1448 * ```typescript
1449 * const story = Story.make(Bank, { layer: BankHandlers, stub: [FraudCheck] });
1450 *
1451 * story(
1452 * Story.when(account, new RecordSettlement({ settlementId: "st_1", amount: 500 })),
1453 * Story.call(Payments.refund, { settlementId: "st_1", amount: 500 }),
1454 * Story.returned(Payments.refund, { refundId: "re_st_1" }),
1455 * ).pipe(Effect.provide(StripePayments));
1456 * ```
1457 *
1458 * **Example:** Fail a call with the operation's declared error, or a defect
1459 * ```typescript
1460 * Story.call(LockVendor.deleteCode, { codeId: "pc_1" }),
1461 * Story.fail(LockVendor.deleteCode, new LockVendorRefused({ reason: "gateway-lost" })),
1462 * Story.call(LockVendor.deleteCode, { codeId: "pc_2" }),
1463 * Story.die(LockVendor.deleteCode, new Error("socket closed")),
1464 * ```
1465 *
1466 * ### Sagas
1467 * **Example:** Check where a saga run is, and send it a signal
1468 * ```typescript
1469 * Story.saga(ExecuteTransfer, transfer, { _tag: "Running" }),
1470 * Story.signal(ExecuteTransfer, transfer, Decision, "approved"),
1471 * ```
1472 *
1473 * @primitive
1474 */
1475 // The steps live on this object rather than as module exports: a module that
1476 // exports `then` is "thenable", and loaders that await module namespaces
1477 // would hang on it.
1478 export const Story = {
1479 make,
1480 given,
1481 when,
1482 // oxlint-disable-next-line unicorn/no-thenable -- `then` is the given/when/then vocabulary
1483 then,
1484 rejected,
1485 replied,
1486 state,
1487 view,
1488 emitted,
1489 streamed,
1490 call: callStep,
1491 succeed,
1492 fail,
1493 die,
1494 returned,
1495 failed,
1496 died,
1497 clock,
1498 advance,
1499 provide,
1500 signal,
1501 saga,
1502 /** Marker for "the view key does not exist". */
1503 none,
1504 } as const;