eutaxy 0.0.0-stage → 0.5.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.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +16 -2
  3. package/dist/aws.d.mts +15464 -0
  4. package/dist/aws.d.mts.map +1 -0
  5. package/dist/aws.mjs +24057 -0
  6. package/dist/aws.mjs.map +1 -0
  7. package/dist/bin.d.mts +1 -0
  8. package/dist/bin.mjs +17 -0
  9. package/dist/bin.mjs.map +1 -0
  10. package/dist/checksum-DhS6ofSm.mjs +6049 -0
  11. package/dist/checksum-DhS6ofSm.mjs.map +1 -0
  12. package/dist/cli-NqY61bpo.mjs +2 -0
  13. package/dist/cli.d.mts +8 -0
  14. package/dist/cli.d.mts.map +1 -0
  15. package/dist/cli.mjs +2 -0
  16. package/dist/cloudflare.d.mts +272 -0
  17. package/dist/cloudflare.d.mts.map +1 -0
  18. package/dist/cloudflare.mjs +1815 -0
  19. package/dist/cloudflare.mjs.map +1 -0
  20. package/dist/es5-DtZuPEgt.mjs +1721 -0
  21. package/dist/es5-DtZuPEgt.mjs.map +1 -0
  22. package/dist/event-streams-BANyO9xt.mjs +801 -0
  23. package/dist/event-streams-BANyO9xt.mjs.map +1 -0
  24. package/dist/explore-BHYvAZKN.d.mts +84 -0
  25. package/dist/explore-BHYvAZKN.d.mts.map +1 -0
  26. package/dist/index.d.mts +252 -0
  27. package/dist/index.d.mts.map +1 -0
  28. package/dist/index.mjs +261 -0
  29. package/dist/index.mjs.map +1 -0
  30. package/dist/platform-eVgCMbX0.d.mts +385 -0
  31. package/dist/platform-eVgCMbX0.d.mts.map +1 -0
  32. package/dist/rolldown-runtime-C1I3wEg2.mjs +43 -0
  33. package/dist/src-BD3jkjgG.mjs +477 -0
  34. package/dist/src-BD3jkjgG.mjs.map +1 -0
  35. package/dist/src-C19_yfMM.mjs +2237 -0
  36. package/dist/src-C19_yfMM.mjs.map +1 -0
  37. package/dist/src-CgfGiH25.mjs +1546 -0
  38. package/dist/src-CgfGiH25.mjs.map +1 -0
  39. package/dist/src-s6uYyC0B.mjs +89 -0
  40. package/dist/src-s6uYyC0B.mjs.map +1 -0
  41. package/dist/verdict-evEM5Gxx.mjs +12 -0
  42. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  43. package/package.json +76 -3
@@ -0,0 +1,2237 @@
1
+ import { i as canonicalJson, n as digestLog, r as emptyLog, t as appendEffect } from "./src-s6uYyC0B.mjs";
2
+ // packages/core/src/prng.ts
3
+ function rotl(x, k) {
4
+ return (x << k | x >>> 32 - k) >>> 0;
5
+ }
6
+ /** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */
7
+ function splitmix32(seed) {
8
+ let a = seed >>> 0;
9
+ return () => {
10
+ a = a + 2654435769 >>> 0;
11
+ let t = a;
12
+ t = Math.imul(t ^ t >>> 16, 569420461);
13
+ t = Math.imul(t ^ t >>> 15, 1935289751);
14
+ return (t ^ t >>> 15) >>> 0;
15
+ };
16
+ }
17
+ /** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */
18
+ function hashString(s) {
19
+ let h = 2166136261;
20
+ for (let i = 0; i < s.length; i++) {
21
+ h ^= s.charCodeAt(i);
22
+ h = Math.imul(h, 16777619);
23
+ }
24
+ return h >>> 0;
25
+ }
26
+ /** Derive an initial state from a number (taken modulo 2^32) or a string. */
27
+ function seedPrng(seed) {
28
+ const next = splitmix32(typeof seed === "string" ? hashString(seed) : seed >>> 0);
29
+ const s = [
30
+ next(),
31
+ next(),
32
+ next(),
33
+ next()
34
+ ];
35
+ if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) s[0] = 1;
36
+ return s;
37
+ }
38
+ /** Next 32-bit unsigned integer and the state that follows it. */
39
+ function nextU32(state) {
40
+ const [s0, s1, s2, s3] = state;
41
+ const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;
42
+ const t = s1 << 9 >>> 0;
43
+ let n2 = (s2 ^ s0) >>> 0;
44
+ let n3 = (s3 ^ s1) >>> 0;
45
+ const n1 = (s1 ^ n2) >>> 0;
46
+ const n0 = (s0 ^ n3) >>> 0;
47
+ n2 = (n2 ^ t) >>> 0;
48
+ n3 = rotl(n3, 11);
49
+ return [result, [
50
+ n0,
51
+ n1,
52
+ n2,
53
+ n3
54
+ ]];
55
+ }
56
+ /** Next float in [0, 1) with 24 bits of precision. */
57
+ function nextFloat(state) {
58
+ const [u, next] = nextU32(state);
59
+ return [(u >>> 8) * 2 ** -24, next];
60
+ }
61
+ /**
62
+ * Next integer in [0, bound). Uses rejection sampling, so every value is
63
+ * equally likely; a bound of 1 always yields 0 without consuming state.
64
+ */
65
+ function nextInt(state, bound) {
66
+ if (!Number.isInteger(bound) || bound < 1 || bound > 4294967296) throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);
67
+ if (bound === 1) return [0, state];
68
+ const limit = 4294967296 - 4294967296 % bound;
69
+ let s = state;
70
+ for (;;) {
71
+ const [u, next] = nextU32(s);
72
+ s = next;
73
+ if (u < limit) return [u % bound, s];
74
+ }
75
+ }
76
+ // packages/core/src/faults.ts
77
+ /**
78
+ * The fault model and the schedule. A schedule is the complete, replayable
79
+ * record of which fault was injected at which effect point in one run.
80
+ */
81
+ /**
82
+ * Decide whether to inject a fault at an effect point during exploration.
83
+ * Pure: the same state and inputs always give the same decision. The PRNG is
84
+ * only consumed when a fault is possible, so adding an ineligible point does
85
+ * not perturb later decisions.
86
+ */
87
+ function decideFault(state, allowed, faultsSoFar, policy) {
88
+ if (allowed.length === 0 || faultsSoFar >= policy.maxFaultsPerRun) return [null, state];
89
+ const [p, s1] = nextFloat(state);
90
+ if (p >= policy.faultProbability) return [null, s1];
91
+ const [i, s2] = nextInt(s1, allowed.length);
92
+ return [allowed[i] ?? null, s2];
93
+ }
94
+ // packages/core/src/invariants.ts
95
+ /**
96
+ * Invariants are plain data describing a property of the effect log; checkers
97
+ * are pure functions from (log, invariant) to a violation or null. The
98
+ * library starts with what the first planted bug needs and grows from there.
99
+ */
100
+ /** Re-derive `expected` for per-message invariants from the bodies that remain. */
101
+ function recomputePerMessageExpected(invariants, bodies) {
102
+ return invariants.map((inv) => {
103
+ if (inv.kind !== "atLeastOnce" || !inv.perMessage) return inv;
104
+ const bodyKey = inv.perMessage.bodyKey;
105
+ const expected = [];
106
+ for (const b of bodies) {
107
+ const v = getPath(b, bodyKey);
108
+ if (v !== void 0) expected.push(v);
109
+ }
110
+ return {
111
+ ...inv,
112
+ expected
113
+ };
114
+ });
115
+ }
116
+ /** The log target decisions of a core function are recorded under. */
117
+ function decisionTarget(fn) {
118
+ return `Core:${fn}`;
119
+ }
120
+ /** The tables in the last snapshot recorded for a target, or undefined when none was. */
121
+ function lastSnapshot(log, target) {
122
+ for (let i = log.entries.length - 1; i >= 0; i--) {
123
+ const e = log.entries[i];
124
+ if (e.kind === "snapshot" && e.target === target) {
125
+ const tables = getPath(e.payload, "tables");
126
+ if (tables && typeof tables === "object" && !Array.isArray(tables)) return tables;
127
+ return {};
128
+ }
129
+ }
130
+ }
131
+ function rowMatches(row, condition) {
132
+ const v = row[condition.column];
133
+ switch (condition.op) {
134
+ case "eq": return v !== void 0 && jsonEqual(v, condition.value);
135
+ case "neq": return v === void 0 || !jsonEqual(v, condition.value);
136
+ case "gt": return typeof v === "number" && v > condition.value;
137
+ case "gte": return typeof v === "number" && v >= condition.value;
138
+ case "lt": return typeof v === "number" && v < condition.value;
139
+ case "lte": return typeof v === "number" && v <= condition.value;
140
+ case "in": return v !== void 0 && condition.value.some((c) => jsonEqual(v, c));
141
+ case "notNull": return v !== void 0 && v !== null;
142
+ }
143
+ }
144
+ /** Rows a state query selects from the log's last snapshot; undefined when there is no snapshot. */
145
+ function queryRows(log, query) {
146
+ const tables = lastSnapshot(log, query.target);
147
+ if (!tables) return void 0;
148
+ const rows = tables[query.table] ?? [];
149
+ const where = query.where ?? [];
150
+ return rows.filter((r) => where.every((c) => rowMatches(r, c)));
151
+ }
152
+ function snapshotSeq(log, target) {
153
+ let last;
154
+ for (const e of log.entries) if (e.kind === "snapshot" && e.target === target) last = e.seq;
155
+ return last === void 0 ? [] : [last];
156
+ }
157
+ /** True when two violations are of the same invariant for the same keys, whatever the traces. */
158
+ function sameViolation(a, b) {
159
+ return a.invariant === b.invariant && a.keys.length === b.keys.length && a.keys.every((k, i) => k === b.keys[i]);
160
+ }
161
+ /** Read a dot path such as "args.params.0" out of JSON data; undefined when absent. */
162
+ function getPath(value, path) {
163
+ let cur = value;
164
+ if (path === "") return cur;
165
+ for (const part of path.split(".")) {
166
+ if (cur === null || typeof cur !== "object") return void 0;
167
+ if (Array.isArray(cur)) {
168
+ const i = Number(part);
169
+ if (!Number.isInteger(i) || i < 0) return void 0;
170
+ cur = cur[i];
171
+ } else cur = cur[part];
172
+ if (cur === void 0) return void 0;
173
+ }
174
+ return cur;
175
+ }
176
+ function jsonEqual(a, b) {
177
+ if (a === void 0) return false;
178
+ if (a === b) return true;
179
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
180
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
181
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i]));
182
+ const ao = a;
183
+ const bo = b;
184
+ const ak = Object.keys(ao).sort();
185
+ const bk = Object.keys(bo).sort();
186
+ return ak.length === bk.length && ak.every((k, i) => k === bk[i] && jsonEqual(ao[k], bo[k]));
187
+ }
188
+ function matches(record, sel) {
189
+ if (record.target !== sel.target) return false;
190
+ if (sel.op !== void 0 && record.op !== sel.op) return false;
191
+ if (sel.kind !== void 0 && record.kind !== sel.kind) return false;
192
+ if (sel.where) {
193
+ for (const [path, want] of Object.entries(sel.where)) if (!jsonEqual(getPath(record.payload, path), want)) return false;
194
+ }
195
+ if (sel.atLeast) for (const [path, min] of Object.entries(sel.atLeast)) {
196
+ const v = getPath(record.payload, path);
197
+ if (typeof v !== "number" || v < min) return false;
198
+ }
199
+ return true;
200
+ }
201
+ function selectEffects(log, sel) {
202
+ return log.entries.filter((e) => matches(e, sel));
203
+ }
204
+ /** Canonical form of a key, so equal JSON values compare equal whatever their key order. */
205
+ function keyOf(record, path) {
206
+ const v = getPath(record.payload, path);
207
+ return v === void 0 ? void 0 : canonicalJson(v);
208
+ }
209
+ function checkInvariant(log, inv) {
210
+ switch (inv.kind) {
211
+ case "refines": return checkRefines(log, inv);
212
+ case "everyRow": return checkEveryRow(log, inv);
213
+ case "implies": return checkImplies(log, inv);
214
+ case "unique": return checkUnique(log, inv);
215
+ case "atMostOncePerKey": {
216
+ const seen = /* @__PURE__ */ new Map();
217
+ for (const e of selectEffects(log, inv.effect)) {
218
+ const k = keyOf(e, inv.key);
219
+ if (k === void 0) continue;
220
+ const first = seen.get(k);
221
+ if (first !== void 0) return {
222
+ invariant: inv.name,
223
+ message: `${inv.effect.target} ${inv.effect.op ?? "*"} happened twice for key ${k} (seq ${first} and ${e.seq})`,
224
+ keys: [k],
225
+ evidence: [first, e.seq]
226
+ };
227
+ seen.set(k, e.seq);
228
+ }
229
+ return null;
230
+ }
231
+ case "atLeastOnce": {
232
+ const present = /* @__PURE__ */ new Set();
233
+ const selected = selectEffects(log, inv.effect);
234
+ for (const e of selected) {
235
+ const k = keyOf(e, inv.key);
236
+ if (k !== void 0) present.add(k);
237
+ }
238
+ const missing = inv.expected.map((v) => canonicalJson(v)).filter((k) => !present.has(k));
239
+ if (missing.length === 0) return null;
240
+ return {
241
+ invariant: inv.name,
242
+ message: `${inv.effect.target} ${inv.effect.op ?? "*"} never happened for key(s) ${missing.join(", ")}`,
243
+ keys: missing,
244
+ evidence: selected.map((e) => e.seq)
245
+ };
246
+ }
247
+ }
248
+ }
249
+ function checkEveryRow(log, inv) {
250
+ const rows = queryRows(log, inv.query);
251
+ if (rows === void 0) return {
252
+ invariant: inv.name,
253
+ message: `no snapshot of ${inv.query.target} was recorded`,
254
+ keys: [],
255
+ evidence: []
256
+ };
257
+ const failing = rows.filter((r) => !inv.holds.every((c) => rowMatches(r, c)));
258
+ if (failing.length === 0) return null;
259
+ const keys = failing.map((r) => canonicalJson(r));
260
+ const shown = keys.slice(0, 3).join(", ") + (failing.length > 3 ? ", …" : "");
261
+ return {
262
+ invariant: inv.name,
263
+ message: `${failing.length} row(s) of ${inv.query.table} in ${inv.query.target} violate the condition: ${shown}`,
264
+ keys,
265
+ evidence: snapshotSeq(log, inv.query.target)
266
+ };
267
+ }
268
+ function checkUnique(log, inv) {
269
+ const rows = queryRows(log, inv.query);
270
+ if (rows === void 0) return {
271
+ invariant: inv.name,
272
+ message: `no snapshot of ${inv.query.target} was recorded`,
273
+ keys: [],
274
+ evidence: []
275
+ };
276
+ const counts = /* @__PURE__ */ new Map();
277
+ for (const r of rows) {
278
+ const v = getPath(r, inv.path);
279
+ if (v === void 0 || v === null) continue;
280
+ const k = canonicalJson(v);
281
+ counts.set(k, (counts.get(k) ?? 0) + 1);
282
+ }
283
+ const shared = [...counts].filter(([, n]) => n > 1);
284
+ if (shared.length === 0) return null;
285
+ const shown = shared.map(([k, n]) => `${n} rows of ${inv.query.table} in ${inv.query.target} share ${inv.path} = ${k}`);
286
+ return {
287
+ invariant: inv.name,
288
+ message: shown.join("; "),
289
+ keys: shared.map(([k]) => k),
290
+ evidence: snapshotSeq(log, inv.query.target)
291
+ };
292
+ }
293
+ function checkImplies(log, inv) {
294
+ const rows = queryRows(log, inv.state);
295
+ if (rows === void 0) return {
296
+ invariant: inv.name,
297
+ message: `no snapshot of ${inv.state.target} was recorded`,
298
+ keys: [],
299
+ evidence: []
300
+ };
301
+ const present = /* @__PURE__ */ new Set();
302
+ for (const r of rows) {
303
+ const v = r[inv.column];
304
+ if (v !== void 0) present.add(canonicalJson(v));
305
+ }
306
+ const missing = [];
307
+ const evidence = [];
308
+ for (const e of selectEffects(log, inv.when)) {
309
+ const k = keyOf(e, inv.key);
310
+ if (k === void 0 || present.has(k)) continue;
311
+ if (!missing.includes(k)) missing.push(k);
312
+ evidence.push(e.seq);
313
+ }
314
+ if (missing.length === 0) return null;
315
+ return {
316
+ invariant: inv.name,
317
+ message: `${inv.when.target} ${inv.when.op ?? "*"} happened for key(s) ${missing.join(", ")} but ${inv.state.table}.${inv.column} in ${inv.state.target} has no such row`,
318
+ keys: missing,
319
+ evidence
320
+ };
321
+ }
322
+ function checkRefines(log, inv) {
323
+ const target = decisionTarget(inv.decision);
324
+ const before = (seq, invocation, pick) => {
325
+ let found;
326
+ for (const e of log.entries) {
327
+ if (e.seq >= seq) break;
328
+ if (e.invocation === invocation && pick(e)) found = e;
329
+ }
330
+ return found;
331
+ };
332
+ for (const effect of selectEffects(log, inv.effect)) {
333
+ const what = `${effect.target} ${effect.op} (seq ${effect.seq}) in ${effect.invocation}`;
334
+ const decision = before(effect.seq, effect.invocation, (e) => e.target === target && e.kind === "result" && getPath(e.payload, "error") === void 0);
335
+ if (!decision) return {
336
+ invariant: inv.name,
337
+ message: `${what} carries out no decision: ${inv.decision} was not called before it in that invocation`,
338
+ keys: ["no_decision"],
339
+ evidence: [effect.seq]
340
+ };
341
+ for (const pair of inv.follows ?? []) {
342
+ const got = getPath(effect.payload, pair.effect);
343
+ const want = getPath(decision.payload, pair.decision);
344
+ if (want === void 0 ? got !== void 0 : !jsonEqual(got, want)) {
345
+ const show = (v) => v === void 0 ? "nothing" : canonicalJson(v);
346
+ return {
347
+ invariant: inv.name,
348
+ message: `${what} does not follow the decision at seq ${decision.seq}: ${pair.effect} is ${show(got)} but the decision's ${pair.decision} is ${show(want)}`,
349
+ keys: ["not_followed", pair.effect],
350
+ evidence: [decision.seq, effect.seq]
351
+ };
352
+ }
353
+ }
354
+ const state = inv.state;
355
+ if (!state) continue;
356
+ const read = before(decision.seq, effect.invocation, (e) => matches(e, state.read));
357
+ if (!read) return {
358
+ invariant: inv.name,
359
+ message: `${what} carries out the decision at seq ${decision.seq}, which rests on no read of the state: ${state.read.target} ${state.read.op ?? "*"} was not read before it in that invocation`,
360
+ keys: ["no_read"],
361
+ evidence: [decision.seq, effect.seq]
362
+ };
363
+ const key = state.key === void 0 ? void 0 : keyOf(read, state.key);
364
+ const write = log.entries.find((e) => e.seq > read.seq && e.seq < effect.seq && e.invocation !== effect.invocation && matches(e, state.write) && (state.key === void 0 || keyOf(e, state.key) === key));
365
+ if (write) return {
366
+ invariant: inv.name,
367
+ message: `${what} carries out a decision made on a stale read: the decision at seq ${decision.seq} rests on the read at seq ${read.seq}${key === void 0 ? "" : ` of ${key}`}, and ${write.invocation} changed it at seq ${write.seq} before the effect committed`,
368
+ keys: ["stale_read", ...key === void 0 ? [] : [key]],
369
+ evidence: [
370
+ read.seq,
371
+ decision.seq,
372
+ write.seq,
373
+ effect.seq
374
+ ]
375
+ };
376
+ }
377
+ return null;
378
+ }
379
+ function checkInvariants(log, invariants) {
380
+ const out = [];
381
+ for (const inv of invariants) {
382
+ const v = checkInvariant(log, inv);
383
+ if (v) out.push(v);
384
+ }
385
+ return out;
386
+ }
387
+ // packages/core/src/scenario.ts
388
+ const defaultBounds = {
389
+ maxFaultsPerRun: 1,
390
+ maxRedeliveries: 2,
391
+ maxConcurrentInvocations: 1,
392
+ budgetMs: 2e3
393
+ };
394
+ function isPositiveInt(n) {
395
+ return typeof n === "number" && Number.isInteger(n) && n > 0;
396
+ }
397
+ /** Every reason a spec is not usable; empty when it is. */
398
+ function validateScenario(spec) {
399
+ const errors = [];
400
+ if (spec.version !== 1) errors.push(`version must be 1, got ${String(spec.version)}`);
401
+ if (!spec.name.trim()) errors.push("name must not be empty");
402
+ if (spec.platform !== void 0 && !spec.platform) errors.push("platform must not be empty when given");
403
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.name)) errors.push(`name must be lowercase letters, digits and dashes: ${JSON.stringify(spec.name)}`);
404
+ if (!spec.worker.entry) errors.push("worker.entry must not be empty");
405
+ if (!spec.worker.config) errors.push("worker.config must not be empty");
406
+ if (!spec.drive.kind) errors.push("drive.kind must not be empty");
407
+ spec.setup.forEach((s, i) => {
408
+ if (!s.kind) errors.push(`setup[${i}].kind must not be empty`);
409
+ });
410
+ if (spec.invariants.length === 0) errors.push("at least one invariant is required");
411
+ const names = /* @__PURE__ */ new Set();
412
+ for (const inv of spec.invariants) {
413
+ if (!inv.name) errors.push("every invariant needs a name");
414
+ else if (names.has(inv.name)) errors.push(`duplicate invariant name ${JSON.stringify(inv.name)}`);
415
+ names.add(inv.name);
416
+ }
417
+ const specs = /* @__PURE__ */ new Set();
418
+ for (const m of spec.specs ?? []) {
419
+ if (!m) errors.push("every specs entry needs a module path");
420
+ else if (specs.has(m)) errors.push(`duplicate specs module ${JSON.stringify(m)}`);
421
+ specs.add(m);
422
+ }
423
+ const ext = /* @__PURE__ */ new Set();
424
+ for (const e of spec.externals) {
425
+ if (!e.name) errors.push("every external needs a name");
426
+ if (ext.has(e.name)) errors.push(`duplicate external ${JSON.stringify(e.name)}`);
427
+ ext.add(e.name);
428
+ if (!e.host) errors.push(`external ${JSON.stringify(e.name)} needs a host`);
429
+ (e.responses ?? []).forEach((r, i) => {
430
+ if (!(Number.isInteger(r.status) && r.status >= 100 && r.status <= 599)) errors.push(`external ${JSON.stringify(e.name)} responses[${i}].status must be an HTTP status`);
431
+ });
432
+ }
433
+ for (const k of [
434
+ "maxFaultsPerRun",
435
+ "maxRedeliveries",
436
+ "maxConcurrentInvocations",
437
+ "budgetMs"
438
+ ]) if (k === "maxFaultsPerRun" || k === "maxRedeliveries") {
439
+ const v = spec.bounds[k];
440
+ if (!(Number.isInteger(v) && v >= 0)) errors.push(`bounds.${k} must be a non-negative integer`);
441
+ } else if (!isPositiveInt(spec.bounds[k])) errors.push(`bounds.${k} must be a positive integer`);
442
+ return errors;
443
+ }
444
+ // packages/core/src/shrink.ts
445
+ /** One-step candidates: each single fault removed, then each single event removed. */
446
+ function shrinkCandidates(state) {
447
+ const out = [];
448
+ state.schedule.faults.forEach((_, i) => {
449
+ out.push({
450
+ schedule: {
451
+ ...state.schedule,
452
+ faults: state.schedule.faults.filter((_, j) => j !== i)
453
+ },
454
+ keepIds: state.keepIds
455
+ });
456
+ });
457
+ if (state.keepIds.length > 1) state.keepIds.forEach((id) => {
458
+ out.push({
459
+ schedule: {
460
+ ...state.schedule,
461
+ faults: state.schedule.faults.filter((f) => !f.invocation.startsWith(`${id}#`))
462
+ },
463
+ keepIds: state.keepIds.filter((k) => k !== id)
464
+ });
465
+ });
466
+ return out;
467
+ }
468
+ // packages/engine/src/context.ts
469
+ /** A new async context slot, or null where the host has no AsyncLocalStorage. */
470
+ function asyncScope() {
471
+ const mod = typeof process !== "undefined" ? process?.getBuiltinModule?.("node:async_hooks") : void 0;
472
+ return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;
473
+ }
474
+ // packages/engine/src/clock.ts
475
+ /**
476
+ * The virtual clock and the globals patch. Within a run, Date, Math.random,
477
+ * crypto.randomUUID, crypto.getRandomValues, performance.now and the timer
478
+ * functions are replaced by deterministic versions driven by the run's seed
479
+ * and by a clock that starts at a fixed epoch and advances only when the
480
+ * engine says so: one millisecond per effect, and to each timer's due time
481
+ * when the timer fires. Timers fire only while the invocation is idle (no
482
+ * effect in flight), in due order, so they never race real I/O.
483
+ */
484
+ /** 2026-01-01T00:00:00.000Z. Every run starts here. */
485
+ const virtualEpoch = Date.UTC(2026, 0, 1);
486
+ const realSetTimeout = globalThis.setTimeout.bind(globalThis);
487
+ const realSetInterval = globalThis.setInterval.bind(globalThis);
488
+ const realClearTimeout = globalThis.clearTimeout.bind(globalThis);
489
+ const realClearInterval = globalThis.clearInterval.bind(globalThis);
490
+ /**
491
+ * Tells library code apart from handler code while an effect's real I/O runs.
492
+ * SDKs back off and time out with timers, which must be real; a handler timer
493
+ * scheduled meanwhile must stay virtual. Node's AsyncLocalStorage follows the
494
+ * library's promise chains and I/O callbacks but not the handler's own
495
+ * continuations. Where it is unavailable (workerd without Node compatibility)
496
+ * every timer stays virtual; the Cloudflare bindings do not use timers.
497
+ */
498
+ const libraryScope = asyncScope();
499
+ var VirtualClock = class {
500
+ time = virtualEpoch;
501
+ timers = [];
502
+ nextId = 1;
503
+ /** The invocation whose code is running; timers scheduled now belong to it. */
504
+ owner = null;
505
+ /** Set by a concurrent run: who is running, asked when a timer is scheduled (overrides `owner`). */
506
+ ownerNow = null;
507
+ /** Set by a concurrent run: binds a callback to the async context it was scheduled in. */
508
+ bind = null;
509
+ now() {
510
+ return this.time;
511
+ }
512
+ advance(ms) {
513
+ if (ms > 0) this.time += ms;
514
+ }
515
+ schedule(callback, delay, args, interval) {
516
+ const ms = Number.isFinite(delay) && delay > 0 ? Math.floor(delay) : 0;
517
+ const timer = {
518
+ id: this.nextId++,
519
+ due: this.time + ms,
520
+ callback: this.bind ? this.bind(callback) : callback,
521
+ args,
522
+ interval,
523
+ owner: this.ownerNow ? this.ownerNow() : this.owner
524
+ };
525
+ this.timers.push(timer);
526
+ return timer.id;
527
+ }
528
+ setTimeout(callback, delay = 0, ...args) {
529
+ return this.schedule(callback, delay, args, null);
530
+ }
531
+ setInterval(callback, delay = 0, ...args) {
532
+ return this.schedule(callback, delay, args, Math.max(1, Math.floor(delay)));
533
+ }
534
+ clear(id) {
535
+ this.timers = this.timers.filter((t) => t.id !== id);
536
+ }
537
+ /** Whether this clock issued the handle (and the timer is still pending). */
538
+ owns(id) {
539
+ return typeof id === "number" && this.timers.some((t) => t.id === id);
540
+ }
541
+ pendingTimers() {
542
+ return this.timers.length;
543
+ }
544
+ /** Drop every timer an invocation scheduled: a crashed invocation's code must never run again. */
545
+ cancelOwner(owner) {
546
+ this.timers = this.timers.filter((t) => t.owner !== owner);
547
+ }
548
+ earliest() {
549
+ let earliest = this.timers[0];
550
+ for (const t of this.timers) if (earliest && (t.due < earliest.due || t.due === earliest.due && t.id < earliest.id)) earliest = t;
551
+ return earliest;
552
+ }
553
+ /** When the next timer is due, or undefined when none is pending. */
554
+ nextDue() {
555
+ return this.earliest()?.due;
556
+ }
557
+ /** Who set the timer `fireNext` would run: an invocation, null for none, undefined when no timer is pending. */
558
+ nextOwner() {
559
+ return this.earliest()?.owner;
560
+ }
561
+ /** Advance to the earliest due timer and run it. False when none is pending. */
562
+ fireNext() {
563
+ const earliest = this.earliest();
564
+ if (!earliest) return false;
565
+ if (earliest.due > this.time) this.time = earliest.due;
566
+ if (earliest.interval === null) this.timers = this.timers.filter((t) => t !== earliest);
567
+ else earliest.due = this.time + earliest.interval;
568
+ try {
569
+ earliest.callback(...earliest.args);
570
+ } catch {}
571
+ return true;
572
+ }
573
+ };
574
+ /** Deterministic randomness for a run: Math.random, UUIDs and random bytes from one seeded stream. */
575
+ var VirtualRandom = class {
576
+ state;
577
+ constructor(seed) {
578
+ this.state = seedPrng(`random:${seed}`);
579
+ }
580
+ float() {
581
+ const [f, next] = nextFloat(this.state);
582
+ this.state = next;
583
+ return f;
584
+ }
585
+ u32() {
586
+ const [u, next] = nextU32(this.state);
587
+ this.state = next;
588
+ return u;
589
+ }
590
+ fill(view) {
591
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
592
+ for (let i = 0; i < bytes.length; i += 4) {
593
+ const u = this.u32();
594
+ for (let j = 0; j < 4 && i + j < bytes.length; j++) bytes[i + j] = u >>> 8 * j & 255;
595
+ }
596
+ return view;
597
+ }
598
+ /** A version-4 UUID from the stream. */
599
+ uuid() {
600
+ const b = this.fill(/* @__PURE__ */ new Uint8Array(16));
601
+ b[6] = b[6] & 15 | 64;
602
+ b[8] = b[8] & 63 | 128;
603
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
604
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
605
+ }
606
+ };
607
+ /** Web Crypto's asynchronous methods: real work that always finishes on its own. */
608
+ const subtleMethods = [
609
+ "encrypt",
610
+ "decrypt",
611
+ "sign",
612
+ "verify",
613
+ "digest",
614
+ "generateKey",
615
+ "deriveKey",
616
+ "deriveBits",
617
+ "importKey",
618
+ "exportKey",
619
+ "wrapKey",
620
+ "unwrapKey"
621
+ ];
622
+ /** Replace the nondeterministic globals for one run. Returns the handle that restores them. */
623
+ function patchGlobals(seed, options = {}) {
624
+ const clock = new VirtualClock();
625
+ const random = new VirtualRandom(seed);
626
+ const reads = { count: 0 };
627
+ const inLibrary = () => libraryScope?.getStore() === true;
628
+ /** Counts a read of the shared virtual state, an effect's own I/O included: its result may depend on it. */
629
+ const read = () => {
630
+ reads.count++;
631
+ };
632
+ const g = globalThis;
633
+ const saved = [];
634
+ const define = (target, key, value) => {
635
+ saved.push({
636
+ target,
637
+ key,
638
+ descriptor: Object.getOwnPropertyDescriptor(target, key)
639
+ });
640
+ Object.defineProperty(target, key, {
641
+ value,
642
+ configurable: true,
643
+ writable: true,
644
+ enumerable: false
645
+ });
646
+ };
647
+ const RealDate = Date;
648
+ const VirtualDate = function(...args) {
649
+ if (new.target === void 0 || args.length === 0) read();
650
+ if (new.target === void 0) return new RealDate(clock.now()).toString();
651
+ return Reflect.construct(RealDate, args.length === 0 ? [clock.now()] : args, new.target);
652
+ };
653
+ Object.setPrototypeOf(VirtualDate, RealDate);
654
+ Object.defineProperty(VirtualDate, "prototype", {
655
+ value: RealDate.prototype,
656
+ writable: false
657
+ });
658
+ Object.defineProperty(VirtualDate, "now", {
659
+ value: () => {
660
+ read();
661
+ return clock.now();
662
+ },
663
+ configurable: true,
664
+ writable: true
665
+ });
666
+ Object.defineProperty(VirtualDate, "name", { value: "Date" });
667
+ define(g, "Date", VirtualDate);
668
+ define(Math, "random", () => {
669
+ read();
670
+ return random.float();
671
+ });
672
+ define(g, "setTimeout", (cb, ms, ...args) => {
673
+ if (inLibrary()) return realSetTimeout(cb, ms, ...args);
674
+ read();
675
+ return clock.setTimeout(cb, ms, ...args);
676
+ });
677
+ define(g, "setInterval", (cb, ms, ...args) => {
678
+ if (inLibrary()) return realSetInterval(cb, ms, ...args);
679
+ read();
680
+ return clock.setInterval(cb, ms, ...args);
681
+ });
682
+ define(g, "clearTimeout", (id) => {
683
+ if (clock.owns(id)) clock.clear(id);
684
+ else realClearTimeout(id);
685
+ });
686
+ define(g, "clearInterval", (id) => {
687
+ if (clock.owns(id)) clock.clear(id);
688
+ else realClearInterval(id);
689
+ });
690
+ const perf = g["performance"];
691
+ if (perf && typeof perf === "object") define(perf, "now", () => {
692
+ read();
693
+ return clock.now() - virtualEpoch;
694
+ });
695
+ const cryptoObj = g["crypto"];
696
+ if (cryptoObj && typeof cryptoObj === "object") {
697
+ define(cryptoObj, "randomUUID", () => {
698
+ read();
699
+ return random.uuid();
700
+ });
701
+ define(cryptoObj, "getRandomValues", (view) => {
702
+ read();
703
+ return random.fill(view);
704
+ });
705
+ const subtle = cryptoObj.subtle;
706
+ const trackIo = options.trackIo;
707
+ if (trackIo && subtle && typeof subtle === "object") for (const name of subtleMethods) {
708
+ const real = subtle[name];
709
+ if (typeof real !== "function") continue;
710
+ define(subtle, name, function(...args) {
711
+ return trackIo(Promise.resolve(real.apply(this, args)));
712
+ });
713
+ }
714
+ }
715
+ let restored = false;
716
+ return {
717
+ clock,
718
+ random,
719
+ reads,
720
+ libraryIo(perform) {
721
+ return libraryScope ? libraryScope.run(true, perform) : perform();
722
+ },
723
+ restore() {
724
+ if (restored) return;
725
+ restored = true;
726
+ for (const { target, key, descriptor } of saved.reverse()) if (descriptor) Object.defineProperty(target, key, descriptor);
727
+ else delete target[key];
728
+ }
729
+ };
730
+ }
731
+ /** A real-time deadline: `expired` resolves after `ms` unless cancelled first. */
732
+ function realDeadline(ms) {
733
+ let handle;
734
+ return {
735
+ expired: new Promise((resolve) => {
736
+ handle = realSetTimeout(() => resolve("expired"), ms);
737
+ }),
738
+ cancel: () => realClearTimeout(handle)
739
+ };
740
+ }
741
+ /** Yield to the real event loop so microtasks and pending I/O can make progress. */
742
+ function realTick() {
743
+ return new Promise((resolve) => realSetTimeout(() => resolve(), 0));
744
+ }
745
+ const realSetImmediate = globalThis.setImmediate?.bind(globalThis);
746
+ /**
747
+ * Let every pending microtask run, and I/O callbacks that are already due:
748
+ * one turn of the real event loop without a timer's delay where the host has
749
+ * `setImmediate`, else a zero timer.
750
+ */
751
+ function drainMicrotasks() {
752
+ return realSetImmediate ? new Promise((resolve) => realSetImmediate(() => resolve())) : realTick();
753
+ }
754
+ /**
755
+ * Wait for a promise under the virtual clock: while it is pending, let real
756
+ * I/O complete, and when the invocation is idle fire the next due timer.
757
+ */
758
+ async function settleOn(promise, ctx) {
759
+ let done = false;
760
+ let failed = false;
761
+ let value;
762
+ let error;
763
+ const tracked = promise.then((v) => {
764
+ done = true;
765
+ value = v;
766
+ }, (e) => {
767
+ done = true;
768
+ failed = true;
769
+ error = e;
770
+ });
771
+ for (;;) {
772
+ await Promise.race([tracked, realTick()]);
773
+ if (done) {
774
+ if (failed) throw error;
775
+ return value;
776
+ }
777
+ if (ctx.crashed()) return new Promise(() => {});
778
+ if (ctx.inFlight() > 0) continue;
779
+ if (ctx.clock.fireNext()) continue;
780
+ ctx.stuck();
781
+ return new Promise(() => {});
782
+ }
783
+ }
784
+ // packages/engine/src/exhaustive.ts
785
+ /** Whether two turns commute: different invocations, effects on different targets. */
786
+ function independent(a, b) {
787
+ return a.invocation !== void 0 && b.invocation !== void 0 && a.invocation !== b.invocation && a.target !== void 0 && b.target !== void 0 && a.target !== b.target;
788
+ }
789
+ const asleep = /* @__PURE__ */ new Map();
790
+ var Enumerator = class {
791
+ stack = [];
792
+ depth = 0;
793
+ /** The depth of the first node in the run just made whose every option was asleep, or null. */
794
+ blockedAt = null;
795
+ mismatchReason = null;
796
+ reduction;
797
+ constructor(options) {
798
+ this.reduction = options.reduction;
799
+ }
800
+ /** Whether the run just made repeats an explored order (every option at some point was asleep). */
801
+ get blocked() {
802
+ return this.blockedAt !== null;
803
+ }
804
+ /** Set when a run made different choices than the same prefix did before: not deterministic. */
805
+ get mismatch() {
806
+ return this.mismatchReason;
807
+ }
808
+ /** The chooser for the next run: the explored prefix, then the first option not asleep. */
809
+ next() {
810
+ this.depth = 0;
811
+ this.blockedAt = null;
812
+ return { choose: (kind, options) => this.choose(kind, options) };
813
+ }
814
+ choose(kind, options) {
815
+ const i = this.depth++;
816
+ const known = this.stack[i];
817
+ if (known) {
818
+ if (!(known.kind === kind && known.options.length === options.length && known.options.every((o, j) => o.label === options[j]?.label)) && this.mismatchReason === null) this.mismatchReason = `choice ${i} differed between runs with the same earlier choices (${known.options.map((o) => o.label).join(", ")} then ${options.map((o) => o.label).join(", ")})`;
819
+ return known.picked < options.length ? known.picked : 0;
820
+ }
821
+ if (this.blockedAt !== null) return 0;
822
+ const sleep = this.sleepAt(i);
823
+ let picked = kind === "turn" ? options.findIndex((o) => !sleep.has(o.label)) : 0;
824
+ if (picked < 0) {
825
+ this.blockedAt = i;
826
+ picked = 0;
827
+ }
828
+ this.stack.push({
829
+ kind,
830
+ options,
831
+ picked,
832
+ done: [],
833
+ sleep
834
+ });
835
+ return picked;
836
+ }
837
+ /** The sleep set of a new node at depth i, from its parent's. */
838
+ sleepAt(i) {
839
+ const parent = this.stack[i - 1];
840
+ if (!this.reduction || !parent) return asleep;
841
+ if (parent.kind === "fault") return parent.sleep;
842
+ const taken = parent.options[parent.picked];
843
+ if (!taken) return asleep;
844
+ const sleep = /* @__PURE__ */ new Map();
845
+ const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];
846
+ for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);
847
+ return sleep;
848
+ }
849
+ /** Move to the next schedule after a run. False once every schedule has been explored. */
850
+ advance() {
851
+ this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);
852
+ while (this.stack.length > 0) {
853
+ const node = this.stack[this.stack.length - 1];
854
+ if (!node.done.includes(node.picked)) node.done.push(node.picked);
855
+ const next = node.options.findIndex((o, j) => !node.done.includes(j) && (node.kind === "fault" || !node.sleep.has(o.label)));
856
+ if (next >= 0) {
857
+ node.picked = next;
858
+ return true;
859
+ }
860
+ this.stack.pop();
861
+ }
862
+ return false;
863
+ }
864
+ };
865
+ // packages/engine/src/fetch.ts
866
+ const FAULTS = [
867
+ "crash_before",
868
+ "crash_after",
869
+ "ambiguous",
870
+ "error"
871
+ ];
872
+ /** Match a host against an exact host or a "*.suffix" pattern. */
873
+ function hostMatches(pattern, host) {
874
+ if (pattern.startsWith("*.")) {
875
+ const suffix = pattern.slice(1);
876
+ return host.endsWith(suffix) && host.length > suffix.length;
877
+ }
878
+ return pattern === host;
879
+ }
880
+ function findExternal(externals, host) {
881
+ return externals.find((e) => hostMatches(e.host, host));
882
+ }
883
+ function findResponse(external, method, path) {
884
+ if (!external.responses) return null;
885
+ return external.responses.find((r) => {
886
+ if (r.method && r.method.toUpperCase() !== method) return false;
887
+ if (r.path === void 0) return true;
888
+ return r.path.endsWith("*") ? path.startsWith(r.path.slice(0, -1)) : r.path === path;
889
+ });
890
+ }
891
+ const REDIRECTS = /* @__PURE__ */ new Set([
892
+ 301,
893
+ 302,
894
+ 303,
895
+ 307,
896
+ 308
897
+ ]);
898
+ function replyOf(r) {
899
+ if (r === null) return {
900
+ status: 200,
901
+ headers: {},
902
+ body: ""
903
+ };
904
+ const json = r.body !== void 0 && typeof r.body !== "string";
905
+ const headers = {};
906
+ for (const [name, value] of Object.entries(r.headers ?? {})) headers[name.toLowerCase()] = value;
907
+ if (json && !("content-type" in headers)) headers["content-type"] = "application/json";
908
+ const body = r.body === void 0 ? "" : json ? JSON.stringify(r.body) : r.body;
909
+ return {
910
+ status: r.status,
911
+ headers,
912
+ body
913
+ };
914
+ }
915
+ function toResponse(reply) {
916
+ return new Response(reply.body === "" ? null : reply.body, {
917
+ status: reply.status,
918
+ headers: reply.headers
919
+ });
920
+ }
921
+ function parseBody(text) {
922
+ if (text === "") return null;
923
+ try {
924
+ return JSON.parse(text);
925
+ } catch {
926
+ return text;
927
+ }
928
+ }
929
+ /**
930
+ * Build the replacement `fetch`. With `hooks`, every request is an effect
931
+ * point recorded as `Fetch:<external>` with the method as op; the result
932
+ * summary carries `status`, `effective` and the dedupe key.
933
+ */
934
+ function createScriptedFetch(externals, hooks, unsupported, afterRequest = () => {}) {
935
+ const dedupe = /* @__PURE__ */ new Map();
936
+ const scripted = (async (input, init) => {
937
+ const request = new Request(input, init);
938
+ const url = new URL(request.url);
939
+ const method = request.method.toUpperCase();
940
+ const external = findExternal(externals, url.host);
941
+ if (!external) {
942
+ unsupported(`fetch to undeclared host ${url.host}; declare it as an external in the scenario`);
943
+ throw new TypeError(`fetch failed: ${url.host} is not a declared external`);
944
+ }
945
+ const headers = {};
946
+ request.headers.forEach((value, name) => {
947
+ headers[name.toLowerCase()] = value;
948
+ });
949
+ const dedupeHeader = external.guarantees.dedupeBy?.toLowerCase();
950
+ const dedupeKey = dedupeHeader ? headers[dedupeHeader] ?? null : null;
951
+ const body = parseBody(await request.text());
952
+ const args = {
953
+ url: request.url,
954
+ method,
955
+ headers,
956
+ body,
957
+ dedupeKey
958
+ };
959
+ const perform = async () => {
960
+ const memo = dedupeKey === null ? null : `${external.name}\u0000${dedupeKey}`;
961
+ if (memo !== null) {
962
+ const earlier = dedupe.get(memo);
963
+ if (earlier) return {
964
+ reply: earlier,
965
+ effective: false
966
+ };
967
+ }
968
+ const script = findResponse(external, method, url.pathname);
969
+ if (script === void 0) {
970
+ unsupported(`no scripted response in external ${external.name} for ${method} ${url.pathname}`);
971
+ throw new TypeError(`fetch failed: no scripted response for ${method} ${url.pathname}`);
972
+ }
973
+ const reply = replyOf(script);
974
+ if (REDIRECTS.has(reply.status) && request.redirect !== "manual") {
975
+ unsupported(`external ${external.name} answers ${method} ${url.pathname} with a ${reply.status} redirect; script the final reply or fetch with redirect: "manual"`);
976
+ throw new TypeError(`fetch failed: redirects are not modelled (${reply.status} from ${url.host})`);
977
+ }
978
+ if (memo !== null) dedupe.set(memo, reply);
979
+ return {
980
+ reply,
981
+ effective: true
982
+ };
983
+ };
984
+ if (!hooks) {
985
+ const { reply } = await perform();
986
+ afterRequest();
987
+ return toResponse(reply);
988
+ }
989
+ const { reply } = await hooks.hooks.effect({
990
+ invocation: hooks.invocation(),
991
+ target: `Fetch:${external.name}`,
992
+ op: method,
993
+ args,
994
+ allowed: FAULTS
995
+ }, perform, (r) => ({
996
+ status: r.reply.status,
997
+ effective: r.effective,
998
+ dedupeKey
999
+ }));
1000
+ return toResponse(reply);
1001
+ });
1002
+ return {
1003
+ fetch: scripted,
1004
+ dedupe
1005
+ };
1006
+ }
1007
+ /** Replace the global `fetch` for a run; returns the function that restores it. */
1008
+ function installScriptedFetch(externals, hooks, unsupported, afterRequest) {
1009
+ const g = globalThis;
1010
+ const saved = Object.getOwnPropertyDescriptor(globalThis, "fetch");
1011
+ const { fetch: scripted } = createScriptedFetch(externals, hooks, unsupported, afterRequest);
1012
+ Object.defineProperty(globalThis, "fetch", {
1013
+ value: scripted,
1014
+ configurable: true,
1015
+ writable: true
1016
+ });
1017
+ let restored = false;
1018
+ return () => {
1019
+ if (restored) return;
1020
+ restored = true;
1021
+ if (saved) Object.defineProperty(globalThis, "fetch", saved);
1022
+ else delete g.fetch;
1023
+ };
1024
+ }
1025
+ /**
1026
+ * Run platform work (a reset, a snapshot) with no network: `fetch` rejects
1027
+ * while it runs. Reports whether anything tried, so code that runs outside
1028
+ * the simulation (an object's constructor during a reset) cannot reach the
1029
+ * network unseen.
1030
+ */
1031
+ async function withoutNetwork(work) {
1032
+ let requested = false;
1033
+ const saved = Object.getOwnPropertyDescriptor(globalThis, "fetch");
1034
+ Object.defineProperty(globalThis, "fetch", {
1035
+ value: async () => {
1036
+ requested = true;
1037
+ throw new TypeError("network access is blocked while Eutaxy resets or snapshots state");
1038
+ },
1039
+ configurable: true,
1040
+ writable: true
1041
+ });
1042
+ try {
1043
+ return {
1044
+ value: await work(),
1045
+ requested
1046
+ };
1047
+ } finally {
1048
+ if (saved) Object.defineProperty(globalThis, "fetch", saved);
1049
+ else delete globalThis.fetch;
1050
+ }
1051
+ }
1052
+ // packages/engine/src/run.ts
1053
+ /**
1054
+ * One run of a scenario: the effect log being built, the fault decisions
1055
+ * (drawn during exploration, looked up during replay), and the invocations
1056
+ * in flight. Proxies in the platform package call `effect`/`effectSync`
1057
+ * around every real effect; everything else is engine-internal.
1058
+ *
1059
+ * With `maxConcurrentInvocations` above 1 the run is concurrent: several
1060
+ * invocations are in flight. Each asynchronous effect is a turn: the
1061
+ * invocation parks there, and once every invocation has parked, finished or
1062
+ * gone idle the run picks which parked one goes next (or whether a new event
1063
+ * starts) from a stream seeded by the schedule's seed. Exploration and
1064
+ * replay make the same picks, so the schedule needs no record of them. Each
1065
+ * delivery runs in its own async context, so an effect is attributed to the
1066
+ * invocation whose code made it even when a promise shared between
1067
+ * invocations resumes one during another's turn.
1068
+ */
1069
+ /** Thrown into user code by a synchronous effect that crashes the invocation. */
1070
+ var CrashSignal = class extends Error {
1071
+ name = "CrashSignal";
1072
+ invocation;
1073
+ constructor(invocation) {
1074
+ super(`invocation ${invocation} crashed by an injected fault`);
1075
+ this.invocation = invocation;
1076
+ }
1077
+ };
1078
+ /** The error user code sees for an injected `error` or `ambiguous` fault. */
1079
+ var InjectedEffectError = class extends Error {
1080
+ name = "InjectedEffectError";
1081
+ point;
1082
+ fault;
1083
+ constructor(point, fault) {
1084
+ super(`${point.target} ${point.op} failed (injected ${fault})`);
1085
+ this.point = point;
1086
+ this.fault = fault;
1087
+ }
1088
+ };
1089
+ var InvocationState = class {
1090
+ crashed;
1091
+ onCrash;
1092
+ /** Effect points seen so far in this invocation; the next effect's ordinal. */
1093
+ ordinal = 0;
1094
+ /** Times this invocation has parked for a turn; names its next turn the same in every run. */
1095
+ parks = 0;
1096
+ crashedFlag = false;
1097
+ resolveCrashed = () => {};
1098
+ id;
1099
+ constructor(id, onCrash) {
1100
+ this.id = id;
1101
+ this.onCrash = onCrash;
1102
+ this.crashed = new Promise((resolve) => {
1103
+ this.resolveCrashed = resolve;
1104
+ });
1105
+ }
1106
+ isCrashed() {
1107
+ return this.crashedFlag;
1108
+ }
1109
+ crash() {
1110
+ if (this.crashedFlag) return;
1111
+ this.crashedFlag = true;
1112
+ this.onCrash();
1113
+ this.resolveCrashed();
1114
+ }
1115
+ };
1116
+ const deliveryScope = asyncScope();
1117
+ /**
1118
+ * An effect being performed. An effect made inside it is nested in it; when
1119
+ * a crash is injected there, the nested effect hangs like any crashed
1120
+ * effect and tells this frame, so the enclosing effect ends too. User code
1121
+ * never sees the crash as an error it could catch.
1122
+ */
1123
+ var Frame = class {
1124
+ /** The invocation whose effect this is. */
1125
+ invocation;
1126
+ /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */
1127
+ hosts;
1128
+ /** False once the effect's perform has ended. */
1129
+ active = true;
1130
+ /** The effect's `onAbandon`, called where the crash happens (inside the hosted code's context). */
1131
+ onAbandon;
1132
+ /** The effect's `mayPark`: whether an effect its hosted code makes may wait for a turn now. */
1133
+ mayPark;
1134
+ /** The hosting effect this one was made inside of and waited for a turn under, if any. */
1135
+ parent;
1136
+ /** Effects the hosted code made that are parked or running now. */
1137
+ children = 0;
1138
+ /** Of those, the ones parked, or running but only waiting on parked effects of their own. */
1139
+ waitingChildren = 0;
1140
+ abandoned = false;
1141
+ wake = () => {};
1142
+ crashed = new Promise((resolve) => {
1143
+ this.wake = () => resolve("nested_crash");
1144
+ });
1145
+ constructor(invocation, hosts, options) {
1146
+ this.invocation = invocation;
1147
+ this.hosts = hosts;
1148
+ this.onAbandon = options.onAbandon;
1149
+ this.mayPark = options.mayPark ?? (() => true);
1150
+ }
1151
+ /** Its hosted code is only waiting on effects of its own that are parked (however deep). */
1152
+ isWaiting() {
1153
+ return this.children > 0 && this.waitingChildren === this.children;
1154
+ }
1155
+ crash() {
1156
+ this.abandon();
1157
+ this.wake();
1158
+ }
1159
+ abandon() {
1160
+ if (this.abandoned) return;
1161
+ this.abandoned = true;
1162
+ this.onAbandon?.();
1163
+ }
1164
+ };
1165
+ /** The frame of the effect whose `perform` the current code runs inside. */
1166
+ const effectScope = asyncScope();
1167
+ /** The run whose globals are installed, if any: where code observed from outside records into. */
1168
+ let installed = null;
1169
+ function installedRun() {
1170
+ return installed;
1171
+ }
1172
+ /** Whether this host can run concurrent invocations: attribution needs async context. */
1173
+ const concurrencySupported = deliveryScope !== null;
1174
+ /** A promise that never settles: how an abandoned invocation experiences a crash. */
1175
+ function hang() {
1176
+ return new Promise(() => {});
1177
+ }
1178
+ var Run = class {
1179
+ logState = emptyLog;
1180
+ faults = [];
1181
+ effectIndex = 0;
1182
+ prng;
1183
+ invocations = /* @__PURE__ */ new Map();
1184
+ reasons = [];
1185
+ inFlight = 0;
1186
+ /** Effects being performed, innermost last (the nesting test where there is no async context). */
1187
+ frames = [];
1188
+ /** Per invocation, its effects with `hostsEffects` being performed, innermost last. */
1189
+ hosting = /* @__PURE__ */ new Map();
1190
+ /** Effects with `hostsEffects` being performed now, across invocations. */
1191
+ hostingNow = 0;
1192
+ patched = null;
1193
+ restoreFetch = null;
1194
+ /** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */
1195
+ current = "";
1196
+ /** Concurrent runs only: invocations waiting at an effect for their turn. */
1197
+ parked = [];
1198
+ /** The turns picked at decisions with more than one option, in order (see Schedule.turns). */
1199
+ turnPicks = [];
1200
+ /** Turns taken from `schedule.turns` so far, when replaying recorded turns. */
1201
+ turnReplayed = 0;
1202
+ /** Events started so far, to name the next start the same in every run. */
1203
+ starts = 0;
1204
+ /** The target of the turn running since the last decision; null for an event's start or none. */
1205
+ turnTarget = null;
1206
+ turnsCommuteNot = false;
1207
+ parkSeq = 0;
1208
+ /** Events a platform queued during a delivery, for the run loop to pick up. */
1209
+ queued = [];
1210
+ /** Concurrent runs only: woken whenever an invocation parks, a delivery ends or I/O completes. */
1211
+ progressWaiters = [];
1212
+ /** Concurrent runs only: the order invocations started in, which orders the parked ones. */
1213
+ startOrder = /* @__PURE__ */ new Map();
1214
+ /** Concurrent runs only: the picks among parked invocations, drawn apart from fault decisions. */
1215
+ turns;
1216
+ /** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */
1217
+ concurrent;
1218
+ options;
1219
+ constructor(options) {
1220
+ this.options = options;
1221
+ this.prng = seedPrng(options.schedule.seed);
1222
+ this.turns = seedPrng(`turns:${options.schedule.seed}`);
1223
+ this.concurrent = options.bounds.maxConcurrentInvocations > 1;
1224
+ }
1225
+ get log() {
1226
+ return this.logState;
1227
+ }
1228
+ /** The schedule as actually executed: input decisions during replay, drawn ones during exploration. */
1229
+ get schedule() {
1230
+ const recorded = this.options.chooser !== void 0 || this.options.schedule.turns !== void 0;
1231
+ return {
1232
+ seed: this.options.schedule.seed,
1233
+ faults: [...this.faults],
1234
+ ...recorded ? { turns: [...this.turnPicks] } : {}
1235
+ };
1236
+ }
1237
+ get effectPoints() {
1238
+ return this.effectIndex;
1239
+ }
1240
+ get faultsInjected() {
1241
+ return this.faults.length;
1242
+ }
1243
+ /**
1244
+ * Whether a turn other than an event's start did more than its own effect:
1245
+ * performed an effect on another target (synchronous, or nested in it),
1246
+ * queued events, or read virtual time or randomness (effects advance the clock and draws the
1247
+ * stream). Turns told apart by their parked effects' targets need not
1248
+ * commute then. A start is ordered against every turn anyway, so what it
1249
+ * does does not count.
1250
+ */
1251
+ get turnsMayNotCommute() {
1252
+ this.endSegment();
1253
+ return this.turnsCommuteNot;
1254
+ }
1255
+ /**
1256
+ * Concurrent runs: events were queued since the last decision (follow-ups
1257
+ * of a delivery that ended, or `enqueue`). The queue's order is shared, so
1258
+ * within a turn this is another dependence.
1259
+ */
1260
+ queuedEvents() {
1261
+ if (this.turnTarget !== null) this.turnsCommuteNot = true;
1262
+ }
1263
+ /** Close the code run since the last decision, noting whether a turn read the shared virtual state. */
1264
+ endSegment() {
1265
+ const reads = this.patched?.reads;
1266
+ if (!reads) return;
1267
+ if (this.turnTarget !== null && reads.count > 0) this.turnsCommuteNot = true;
1268
+ reads.count = 0;
1269
+ }
1270
+ get unsupportedReasons() {
1271
+ return this.reasons;
1272
+ }
1273
+ /** Replace the nondeterministic globals and `fetch` for this run. Call `uninstall` in a finally. */
1274
+ install(externals = []) {
1275
+ installed = this;
1276
+ if (!this.patched) {
1277
+ this.patched = patchGlobals(this.options.schedule.seed, { trackIo: (work) => {
1278
+ this.inFlight++;
1279
+ return work.finally(() => {
1280
+ this.inFlight--;
1281
+ if (this.concurrent) this.progressed();
1282
+ });
1283
+ } });
1284
+ if (this.concurrent) {
1285
+ const clock = this.patched.clock;
1286
+ clock.ownerNow = () => this.running();
1287
+ clock.bind = (callback) => {
1288
+ const cell = deliveryScope?.getStore();
1289
+ if (!cell || !deliveryScope) return callback;
1290
+ const scope = deliveryScope;
1291
+ return (...args) => scope.run(cell, () => callback(...args));
1292
+ };
1293
+ }
1294
+ }
1295
+ if (!this.restoreFetch) this.restoreFetch = installScriptedFetch(externals, {
1296
+ hooks: this,
1297
+ invocation: () => this.running()
1298
+ }, (reason) => this.unsupported(reason));
1299
+ }
1300
+ uninstall() {
1301
+ if (installed === this) installed = null;
1302
+ this.restoreFetch?.();
1303
+ this.restoreFetch = null;
1304
+ this.patched?.restore();
1305
+ this.patched = null;
1306
+ }
1307
+ /** Virtual milliseconds since the epoch, or the real clock when the globals are not installed. */
1308
+ now() {
1309
+ return this.patched ? this.patched.clock.now() : Date.now();
1310
+ }
1311
+ /** Timers scheduled and not yet fired or cancelled (0 when the globals are not installed). */
1312
+ pendingTimers() {
1313
+ return this.patched?.clock.pendingTimers() ?? 0;
1314
+ }
1315
+ startInvocation(id, options = {}) {
1316
+ if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);
1317
+ const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));
1318
+ this.invocations.set(id, inv);
1319
+ if (options.bookkeeping) return inv;
1320
+ if (this.concurrent) {
1321
+ this.startOrder.set(id, this.startOrder.size);
1322
+ const cell = deliveryScope?.getStore();
1323
+ if (cell && cell.id === null) {
1324
+ cell.id = id;
1325
+ this.runAs(id);
1326
+ }
1327
+ return inv;
1328
+ }
1329
+ this.runAs(id);
1330
+ return inv;
1331
+ }
1332
+ enqueue(event) {
1333
+ this.queued.push(event);
1334
+ if (this.concurrent) this.progressed();
1335
+ }
1336
+ /** Events platforms queued with `enqueue` since the last call. */
1337
+ takeQueued() {
1338
+ const queued = this.queued;
1339
+ this.queued = [];
1340
+ return queued;
1341
+ }
1342
+ hostingFrames(invocation) {
1343
+ let frames = this.hosting.get(invocation);
1344
+ if (!frames) {
1345
+ frames = [];
1346
+ this.hosting.set(invocation, frames);
1347
+ }
1348
+ return frames;
1349
+ }
1350
+ running() {
1351
+ if (!this.concurrent) return this.current;
1352
+ return deliveryScope?.getStore()?.id ?? this.current;
1353
+ }
1354
+ runAs(id) {
1355
+ if (this.patched) this.patched.clock.owner = id;
1356
+ if (id !== null) this.current = id;
1357
+ }
1358
+ invocation(id) {
1359
+ const inv = this.invocations.get(id);
1360
+ if (!inv) throw new Error(`effect from unknown invocation ${id}`);
1361
+ return inv;
1362
+ }
1363
+ decide(point, ordinal) {
1364
+ const chooser = this.options.chooser;
1365
+ if (chooser && this.options.mode === "explore") {
1366
+ if (point.allowed.length === 0 || this.faults.length >= this.options.bounds.maxFaultsPerRun) return null;
1367
+ const i = chooser.choose("fault", [{ label: "none" }, ...point.allowed.map((f) => ({ label: f }))]);
1368
+ return i === 0 ? null : point.allowed[i - 1] ?? null;
1369
+ }
1370
+ if (this.options.mode === "replay") {
1371
+ const d = this.options.schedule.faults.find((f) => f.invocation === point.invocation && f.ordinal === ordinal);
1372
+ return d && point.allowed.includes(d.fault) ? d.fault : null;
1373
+ }
1374
+ const [fault, next] = decideFault(this.prng, point.allowed, this.faults.length, {
1375
+ maxFaultsPerRun: this.options.bounds.maxFaultsPerRun,
1376
+ faultProbability: this.options.faultProbability
1377
+ });
1378
+ this.prng = next;
1379
+ return fault;
1380
+ }
1381
+ record(point, kind, payload) {
1382
+ if (kind === "result" && this.turnTarget !== null && point.target !== this.turnTarget) this.turnsCommuteNot = true;
1383
+ this.logState = appendEffect(this.logState, {
1384
+ kind,
1385
+ invocation: point.invocation,
1386
+ target: point.target,
1387
+ op: point.op,
1388
+ payload
1389
+ });
1390
+ }
1391
+ /** Open an effect point: record the call and decide the fault. */
1392
+ open(point, inv) {
1393
+ this.effectIndex++;
1394
+ const ordinal = inv.ordinal++;
1395
+ this.record(point, "call", { args: point.args });
1396
+ const fault = this.decide(point, ordinal);
1397
+ if (fault) this.faults.push({
1398
+ invocation: point.invocation,
1399
+ ordinal,
1400
+ fault,
1401
+ target: point.target,
1402
+ op: point.op
1403
+ });
1404
+ return fault;
1405
+ }
1406
+ async effect(point, perform, summarize, options = {}) {
1407
+ const inv = this.invocation(point.invocation);
1408
+ if (inv.isCrashed()) return hang();
1409
+ const store = effectScope?.getStore();
1410
+ const live = store?.active && store.invocation === point.invocation ? store : void 0;
1411
+ const enclosing = effectScope ? live ?? this.hosting.get(point.invocation)?.at(-1) : this.frames.at(-1);
1412
+ const nested = enclosing !== void 0;
1413
+ if (this.concurrent && !nested) {
1414
+ await new Promise((go) => {
1415
+ this.parked.push({
1416
+ inv,
1417
+ seq: this.parkSeq++,
1418
+ go,
1419
+ option: this.turnOption(inv, point)
1420
+ });
1421
+ this.progressed();
1422
+ });
1423
+ if (inv.isCrashed()) return hang();
1424
+ } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {
1425
+ const host = enclosing;
1426
+ let released = false;
1427
+ this.adjust(host, () => {
1428
+ host.children++;
1429
+ host.waitingChildren++;
1430
+ });
1431
+ this.parked.push({
1432
+ inv,
1433
+ seq: this.parkSeq++,
1434
+ go: () => released = true,
1435
+ host,
1436
+ option: this.turnOption(inv, point)
1437
+ });
1438
+ this.progressed();
1439
+ while (!released && !inv.isCrashed()) await realTick();
1440
+ if (!released) {
1441
+ this.adjust(host, () => {
1442
+ host.children--;
1443
+ host.waitingChildren--;
1444
+ });
1445
+ return hang();
1446
+ }
1447
+ try {
1448
+ return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
1449
+ } finally {
1450
+ this.adjust(host, () => host.children--);
1451
+ }
1452
+ }
1453
+ return this.performEffect(point, perform, summarize, options, inv, enclosing);
1454
+ }
1455
+ /**
1456
+ * Change a hosting frame's children and keep `inFlight` in step: a frame
1457
+ * counts in flight unless it is only waiting on parked effects of its own,
1458
+ * and a frame that starts or stops waiting does so for its parent too.
1459
+ */
1460
+ adjust(frame, change) {
1461
+ const before = frame.isWaiting();
1462
+ change();
1463
+ const after = frame.isWaiting();
1464
+ if (before === after) return;
1465
+ if (frame.active) this.inFlight += after ? -1 : 1;
1466
+ const parent = frame.parent;
1467
+ if (frame.active && parent) this.adjust(parent, () => parent.waitingChildren += after ? 1 : -1);
1468
+ }
1469
+ /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
1470
+ async performEffect(point, perform, summarize, options, inv, enclosing, host) {
1471
+ const dead = () => {
1472
+ enclosing?.crash();
1473
+ return hang();
1474
+ };
1475
+ const fault = this.open(point, inv);
1476
+ if (fault === "crash_before" || fault === "cut_off") {
1477
+ this.record(point, "fault", {
1478
+ args: point.args,
1479
+ fault
1480
+ });
1481
+ inv.crash();
1482
+ return dead();
1483
+ }
1484
+ if (fault === "error") {
1485
+ this.record(point, "fault", {
1486
+ args: point.args,
1487
+ fault
1488
+ });
1489
+ throw new InjectedEffectError(point, fault);
1490
+ }
1491
+ let settled;
1492
+ const deadline = realDeadline(this.options.bounds.budgetMs);
1493
+ const frame = new Frame(point.invocation, point.hostsEffects === true, options);
1494
+ frame.parent = host;
1495
+ const hosted = point.hostsEffects ? this.hostingFrames(point.invocation) : void 0;
1496
+ this.inFlight++;
1497
+ this.frames.push(frame);
1498
+ hosted?.push(frame);
1499
+ if (hosted) this.hostingNow++;
1500
+ try {
1501
+ const inside = () => effectScope ? effectScope.run(frame, perform) : perform();
1502
+ const io = this.patched ? this.patched.libraryIo(inside) : inside();
1503
+ settled = await Promise.race([
1504
+ io.then((value) => ({
1505
+ ok: true,
1506
+ value
1507
+ }), (error) => ({
1508
+ ok: false,
1509
+ error
1510
+ })),
1511
+ deadline.expired,
1512
+ frame.crashed
1513
+ ]);
1514
+ } catch (err) {
1515
+ settled = {
1516
+ ok: false,
1517
+ error: err
1518
+ };
1519
+ } finally {
1520
+ deadline.cancel();
1521
+ if (hosted) {
1522
+ hosted.splice(hosted.lastIndexOf(frame), 1);
1523
+ this.hostingNow--;
1524
+ }
1525
+ this.frames.splice(this.frames.lastIndexOf(frame), 1);
1526
+ if (!frame.isWaiting()) this.inFlight--;
1527
+ else if (frame.parent) {
1528
+ const parent = frame.parent;
1529
+ this.adjust(parent, () => parent.waitingChildren--);
1530
+ }
1531
+ frame.active = false;
1532
+ frame.parent = void 0;
1533
+ this.patched?.clock.advance(1);
1534
+ if (this.concurrent) this.progressed();
1535
+ }
1536
+ if (settled === "expired") {
1537
+ this.unsupported(`${point.target} ${point.op} did not complete within ${this.options.bounds.budgetMs} ms of real time`);
1538
+ inv.crash();
1539
+ frame.abandon();
1540
+ return hang();
1541
+ }
1542
+ if (settled === "nested_crash") return dead();
1543
+ if (!settled.ok) {
1544
+ this.record(point, "result", {
1545
+ args: point.args,
1546
+ result: null,
1547
+ error: String(settled.error)
1548
+ });
1549
+ throw settled.error;
1550
+ }
1551
+ const value = settled.value;
1552
+ this.record(point, "result", {
1553
+ args: point.args,
1554
+ result: summarize(value)
1555
+ });
1556
+ if (inv.isCrashed()) return hang();
1557
+ if (fault === "crash_after") {
1558
+ this.record(point, "fault", {
1559
+ args: point.args,
1560
+ fault
1561
+ });
1562
+ inv.crash();
1563
+ return dead();
1564
+ }
1565
+ if (fault === "ambiguous") {
1566
+ this.record(point, "fault", {
1567
+ args: point.args,
1568
+ fault
1569
+ });
1570
+ throw new InjectedEffectError(point, fault);
1571
+ }
1572
+ return value;
1573
+ }
1574
+ effectSync(point, perform, summarize) {
1575
+ const inv = this.invocation(point.invocation);
1576
+ if (inv.isCrashed()) throw new CrashSignal(inv.id);
1577
+ const fault = this.open(point, inv);
1578
+ if (fault === "crash_before" || fault === "cut_off") {
1579
+ this.record(point, "fault", {
1580
+ args: point.args,
1581
+ fault
1582
+ });
1583
+ inv.crash();
1584
+ throw new CrashSignal(inv.id);
1585
+ }
1586
+ if (fault === "error") {
1587
+ this.record(point, "fault", {
1588
+ args: point.args,
1589
+ fault
1590
+ });
1591
+ throw new InjectedEffectError(point, fault);
1592
+ }
1593
+ let value;
1594
+ try {
1595
+ value = perform();
1596
+ } catch (err) {
1597
+ this.record(point, "result", {
1598
+ args: point.args,
1599
+ result: null,
1600
+ error: String(err)
1601
+ });
1602
+ throw err;
1603
+ }
1604
+ this.record(point, "result", {
1605
+ args: point.args,
1606
+ result: summarize(value)
1607
+ });
1608
+ if (fault === "crash_after") {
1609
+ this.record(point, "fault", {
1610
+ args: point.args,
1611
+ fault
1612
+ });
1613
+ inv.crash();
1614
+ throw new CrashSignal(inv.id);
1615
+ }
1616
+ if (fault === "ambiguous") {
1617
+ this.record(point, "fault", {
1618
+ args: point.args,
1619
+ fault
1620
+ });
1621
+ throw new InjectedEffectError(point, fault);
1622
+ }
1623
+ return value;
1624
+ }
1625
+ unsupported(reason) {
1626
+ this.reasons.push(reason);
1627
+ }
1628
+ settle(promise, invocation) {
1629
+ const inv = this.invocation(invocation);
1630
+ if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang())]);
1631
+ const patched = this.patched;
1632
+ if (patched) patched.clock.owner = invocation;
1633
+ this.current = invocation;
1634
+ if (!patched) return Promise.race([promise, inv.crashed.then(() => new Promise(() => {}))]);
1635
+ return settleOn(promise, {
1636
+ clock: patched.clock,
1637
+ inFlight: () => this.inFlight,
1638
+ crashed: () => inv.isCrashed(),
1639
+ stuck: () => {
1640
+ this.unsupported(`invocation ${invocation} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`);
1641
+ inv.crash();
1642
+ }
1643
+ });
1644
+ }
1645
+ /** Concurrent runs: start a delivery in its own async context. */
1646
+ startDelivery(deliver) {
1647
+ if (!deliveryScope) throw new Error("concurrent invocations need AsyncLocalStorage");
1648
+ const cell = { id: null };
1649
+ this.runAs(null);
1650
+ return {
1651
+ promise: deliveryScope.run(cell, deliver),
1652
+ invocation: () => cell.id
1653
+ };
1654
+ }
1655
+ /** Concurrent runs: something moved (an invocation parked, a delivery ended, I/O completed). */
1656
+ progressed() {
1657
+ if (this.hostingNow > 0) return;
1658
+ const waiters = this.progressWaiters;
1659
+ this.progressWaiters = [];
1660
+ for (const wake of waiters) wake();
1661
+ }
1662
+ /**
1663
+ * Concurrent runs: wait until the running invocation has parked, finished
1664
+ * or gone idle. Parking, a delivery ending and I/O completing wake the wait
1665
+ * at once; then every pending microtask runs, so continuations the turn set
1666
+ * off have run too. Code waiting on anything else gets one zero timer, the
1667
+ * same allowance the sequential path gives, before it counts as idle.
1668
+ */
1669
+ async quiesce() {
1670
+ for (;;) {
1671
+ await Promise.race([new Promise((wake) => this.progressWaiters.push(wake)), realTick()]);
1672
+ await drainMicrotasks();
1673
+ if (this.inFlight === 0) return;
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Concurrent runs: pick the next turn among the parked invocations and,
1678
+ * when `canStart`, starting the next event. Parked invocations are ordered
1679
+ * by start, then by when they parked, so the pick does not depend on
1680
+ * real-time arrival. Returns what was picked; "turn" has already released it.
1681
+ */
1682
+ takeTurn(canStart) {
1683
+ const order = (inv) => this.startOrder.get(inv.id) ?? 0;
1684
+ this.parked = this.parked.filter((p) => !p.inv.isCrashed()).sort((a, b) => order(a.inv) - order(b.inv) || a.seq - b.seq);
1685
+ const options = this.parked.length + (canStart ? 1 : 0);
1686
+ this.endSegment();
1687
+ this.turnTarget = null;
1688
+ if (options === 0) return "none";
1689
+ let pick = 0;
1690
+ if (options > 1) {
1691
+ pick = this.pickTurn(options, canStart);
1692
+ this.turnPicks.push(pick);
1693
+ } else if (this.options.chooser && this.options.mode === "explore") this.options.chooser.choose("turn", this.turnOptions(canStart));
1694
+ const [chosen] = pick < this.parked.length ? this.parked.splice(pick, 1) : [];
1695
+ if (!chosen) {
1696
+ this.starts++;
1697
+ return "start";
1698
+ }
1699
+ this.turnTarget = chosen.option.target ?? null;
1700
+ this.runAs(chosen.inv.id);
1701
+ const host = chosen.host;
1702
+ if (host) this.adjust(host, () => host.waitingChildren--);
1703
+ chosen.go();
1704
+ return "turn";
1705
+ }
1706
+ /** A parked invocation's next turn as a choice. */
1707
+ turnOption(inv, point) {
1708
+ return {
1709
+ label: `${inv.id}@${inv.parks++}`,
1710
+ invocation: inv.id,
1711
+ target: point.target
1712
+ };
1713
+ }
1714
+ /** The turns on offer, as choices: the parked invocations in order, then starting the next event. */
1715
+ turnOptions(canStart) {
1716
+ return [...this.parked.map((p) => p.option), ...canStart ? [{ label: `start:${this.starts}` }] : []];
1717
+ }
1718
+ /** The turn at a decision with more than one option: recorded, chosen, or drawn from the seed. */
1719
+ pickTurn(options, canStart) {
1720
+ const recorded = this.options.schedule.turns;
1721
+ if (this.options.mode === "replay" && recorded) {
1722
+ const i = recorded[this.turnReplayed++] ?? 0;
1723
+ return i < options ? i : 0;
1724
+ }
1725
+ const chooser = this.options.chooser;
1726
+ if (chooser && this.options.mode === "explore") return chooser.choose("turn", this.turnOptions(canStart));
1727
+ const [i, next] = nextInt(this.turns, options);
1728
+ this.turns = next;
1729
+ return i;
1730
+ }
1731
+ /**
1732
+ * Let virtual time pass until `at`: timers due by then fire first, in due
1733
+ * order, as the invocations that set them, each followed by the work it
1734
+ * sets off. No-op when `at` is not ahead.
1735
+ */
1736
+ async advanceTo(at) {
1737
+ const clock = this.patched?.clock;
1738
+ if (!clock) return;
1739
+ for (let due = clock.nextDue(); due !== void 0 && due <= at; due = clock.nextDue()) {
1740
+ this.runAs(clock.nextOwner() ?? null);
1741
+ clock.fireNext();
1742
+ do
1743
+ await drainMicrotasks();
1744
+ while (this.inFlight > 0);
1745
+ }
1746
+ clock.advance(at - clock.now());
1747
+ }
1748
+ /** When the next virtual timer is due, or undefined when none is pending. */
1749
+ nextTimerDue() {
1750
+ return this.patched?.clock.nextDue();
1751
+ }
1752
+ /** Concurrent runs: fire the next due timer as the invocation that set it. False when none is pending. */
1753
+ fireTimer() {
1754
+ const clock = this.patched?.clock;
1755
+ if (!clock) return false;
1756
+ const owner = clock.nextOwner();
1757
+ if (owner === void 0) return false;
1758
+ this.runAs(owner);
1759
+ return clock.fireNext();
1760
+ }
1761
+ /**
1762
+ * Concurrent runs: nothing can make progress; abandon these invocations so
1763
+ * the run can end. Returns how many were still alive.
1764
+ */
1765
+ abandon(ids) {
1766
+ let abandoned = 0;
1767
+ for (const id of ids) {
1768
+ const inv = this.invocations.get(id);
1769
+ if (!inv || inv.isCrashed()) continue;
1770
+ this.unsupported(`invocation ${id} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`);
1771
+ inv.crash();
1772
+ abandoned++;
1773
+ }
1774
+ return abandoned;
1775
+ }
1776
+ /** A call of a pure core function, recorded as a decision of the invocation running now (see `observeCore`). */
1777
+ decision(fn, payload) {
1778
+ this.logState = appendEffect(this.logState, {
1779
+ kind: "result",
1780
+ invocation: this.running(),
1781
+ target: decisionTarget(fn),
1782
+ op: "decide",
1783
+ payload
1784
+ });
1785
+ }
1786
+ snapshot(invocation, target, payload) {
1787
+ this.logState = appendEffect(this.logState, {
1788
+ kind: "snapshot",
1789
+ invocation,
1790
+ target,
1791
+ op: "snapshot",
1792
+ payload
1793
+ });
1794
+ }
1795
+ };
1796
+ // packages/engine/src/shrink.ts
1797
+ /**
1798
+ * Shrinking, the loop: try the pure candidates in order, replay each, keep
1799
+ * the first that still violates the same invariant for the same keys, and
1800
+ * repeat from there until nothing smaller works or the budget is spent.
1801
+ */
1802
+ /** The scenario restricted to the kept events, with per-message invariants re-derived. */
1803
+ function restrictSpec(platform, spec, keepIds) {
1804
+ const restricted = platform.restrictEvents(spec, keepIds);
1805
+ const bodies = platform.initialEvents(restricted).map((e) => e.data);
1806
+ return {
1807
+ ...restricted,
1808
+ invariants: recomputePerMessageExpected(restricted.invariants, bodies)
1809
+ };
1810
+ }
1811
+ async function shrink(spec, platform, schedule, violation, trace, options) {
1812
+ const allIds = platform.initialEvents(spec).map((e) => e.id);
1813
+ let state = {
1814
+ schedule,
1815
+ keepIds: allIds
1816
+ };
1817
+ let best = {
1818
+ trace,
1819
+ violation
1820
+ };
1821
+ let runs = 0;
1822
+ let improved = true;
1823
+ while (improved && runs < options.maxRuns && options.now() < options.deadline) {
1824
+ improved = false;
1825
+ for (const candidate of shrinkCandidates(state)) {
1826
+ if (runs >= options.maxRuns || options.now() >= options.deadline) break;
1827
+ const candidateSpec = restrictSpec(platform, spec, candidate.keepIds);
1828
+ const run = await replayRun(candidateSpec, platform, candidate.schedule);
1829
+ const log = run.log;
1830
+ runs++;
1831
+ if (run.unsupportedReasons.length > 0) continue;
1832
+ const found = checkInvariants(log, candidateSpec.invariants).find((v) => sameViolation(v, violation));
1833
+ if (found) {
1834
+ state = candidate;
1835
+ best = {
1836
+ trace: log,
1837
+ violation: found
1838
+ };
1839
+ improved = true;
1840
+ break;
1841
+ }
1842
+ }
1843
+ }
1844
+ return {
1845
+ spec: restrictSpec(platform, spec, state.keepIds),
1846
+ schedule: state.schedule,
1847
+ keptEvents: state.keepIds,
1848
+ trace: best.trace,
1849
+ violation: best.violation,
1850
+ runs,
1851
+ faultsRemoved: schedule.faults.length - state.schedule.faults.length,
1852
+ eventsRemoved: allIds.length - state.keepIds.length
1853
+ };
1854
+ }
1855
+ // packages/engine/src/explore.ts
1856
+ /**
1857
+ * The exploration loop: run the scenario under seeded fault injection until
1858
+ * an invariant breaks or the budget is spent; replay any violation before
1859
+ * reporting it.
1860
+ */
1861
+ const engineAssumptions = [
1862
+ "schedule points are effect boundaries: proxied bindings, patched timers and fetch; other awaits run in program order",
1863
+ "faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model",
1864
+ "Date, Math.random, crypto.randomUUID, crypto.getRandomValues, performance.now and timers are virtualised per run from the seed; time starts at 2026-01-01T00:00:00Z and advances 1 ms per effect and to each timer's due time",
1865
+ "timers fire only while the invocation is idle (no effect in flight), in due order; an invocation waiting on something outside Eutaxy makes the run UNSUPPORTED",
1866
+ "an effect whose real I/O takes longer than the scenario's budgetMs is treated as hung: the run is UNSUPPORTED and names the effect",
1867
+ "while an effect performs real I/O, timers the library schedules inside that I/O are real (backoff, timeouts) and timers the handler schedules meanwhile stay virtual, told apart by async context; without async context support every timer stays virtual",
1868
+ "module-level state cannot be reset between runs; before BOUNDED the first runs are replayed in reverse order and any difference makes the run UNSUPPORTED (module_state_leak)",
1869
+ "outbound fetch never reaches the network: requests are answered from the scenario's declared externals, an external's dedupeBy guarantee is honoured by replaying the first response per key, and an undeclared host makes the run UNSUPPORTED"
1870
+ ];
1871
+ /** What a verdict rests on about concurrency, for these bounds. */
1872
+ function concurrencyAssumption(bounds) {
1873
+ if (bounds.maxConcurrentInvocations === 1) return "one invocation at a time (maxConcurrentInvocations = 1)";
1874
+ return `up to ${bounds.maxConcurrentInvocations} invocations in flight, interleaved only at asynchronous effects (proxied bindings, fetch): code between two such effects runs without interruption (except continuations of a promise it settles for another invocation, which run then and are still attributed to their own invocation), Web Crypto calls are waited for like I/O, other non-effect awaits (body reads included) settle within one turn of the event loop, synchronous effects are not interleaving points, an effect made by code another effect hosts (an object calling out during a call) is a turn of its own unless that code cannot be interrupted (an object inside blockConcurrencyWhile), when it runs within the hosting effect's turn, the next turn is a seeded pick among parked invocations, whether a new event starts while a slot is free is a seeded pick too, and timers fire only when no invocation can take a turn`;
1875
+ }
1876
+ /** The pending event to deliver next: the earliest by `at`, then the first queued. */
1877
+ function nextEvent(pending) {
1878
+ let best = 0;
1879
+ for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
1880
+ return best;
1881
+ }
1882
+ /** What a verdict rests on about how schedules were chosen, when exploration was exhaustive. */
1883
+ function explorationAssumption(options) {
1884
+ if (!options.exhaustive) return [];
1885
+ return ["exhaustive: every placement of faults within maxFaultsPerRun and every order of turns, each run once, until complete or the budget ends (reached.exhaustive says which)", ...(typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true) ? ["partial-order reduction: turns of different invocations whose effects have different targets commute, so one order of them is run; this assumes code between an invocation's effects shares no state with other invocations except through effects and the virtual globals, and once a turn other than an event's start performs an effect on another target than its own, queues an event, or reads virtual time or randomness, or schedules a timer, the reduction is off and every order is run (reached.exhaustive.reduction says whether it stayed on)"] : []];
1886
+ }
1887
+ /** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
1888
+ async function deliverInOrder(spec, platform, run) {
1889
+ const pending = [...platform.initialEvents(spec)];
1890
+ while (pending.length > 0) {
1891
+ const [event] = pending.splice(nextEvent(pending), 1);
1892
+ if (event.at !== void 0) await run.advanceTo(event.at);
1893
+ const result = await platform.deliver(event, run, spec);
1894
+ pending.push(...run.takeQueued(), ...result.followUps);
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
1899
+ * is a seeded pick: one parked invocation performs its effect and runs to
1900
+ * its next one, or, while a slot is free, the next event starts. When
1901
+ * nothing is parked and no event can start a timer fires, and when nothing
1902
+ * can move the remaining invocations are abandoned.
1903
+ */
1904
+ async function deliverConcurrently(spec, platform, run) {
1905
+ const pending = [...platform.initialEvents(spec)];
1906
+ let active = [];
1907
+ for (;;) {
1908
+ const queuedBefore = pending.length;
1909
+ for (const d of active) {
1910
+ if (!d.outcome) continue;
1911
+ if ("error" in d.outcome) throw d.outcome.error;
1912
+ pending.push(...d.outcome.result.followUps);
1913
+ }
1914
+ active = active.filter((d) => !d.outcome);
1915
+ pending.push(...run.takeQueued());
1916
+ if (pending.length > queuedBefore) run.queuedEvents();
1917
+ if (active.length === 0 && pending.length === 0) return;
1918
+ const next = pending.length > 0 ? nextEvent(pending) : -1;
1919
+ const due = next >= 0 && (pending[next]?.at ?? 0) <= run.now();
1920
+ const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;
1921
+ const turn = run.takeTurn(canStart);
1922
+ if (turn === "start") {
1923
+ const [event] = pending.splice(next, 1);
1924
+ const d = {
1925
+ started: run.startDelivery(() => platform.deliver(event, run, spec)),
1926
+ outcome: null
1927
+ };
1928
+ d.started.promise.then((result) => {
1929
+ d.outcome = { result };
1930
+ run.progressed();
1931
+ }, (error) => {
1932
+ d.outcome = { error };
1933
+ run.progressed();
1934
+ });
1935
+ active.push(d);
1936
+ } else if (turn === "none" && next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (run.nextTimerDue() ?? Number.POSITIVE_INFINITY) > (pending[next]?.at ?? 0)) await run.advanceTo(pending[next]?.at ?? 0);
1937
+ else if (turn === "none" && !run.fireTimer()) {
1938
+ const stuck = active.flatMap((d) => d.started.invocation() ?? []);
1939
+ if (run.abandon(stuck) === 0) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
1940
+ }
1941
+ await run.quiesce();
1942
+ }
1943
+ }
1944
+ /** Run the scenario once under the given run's fault decisions and return its log. */
1945
+ async function runOnce(spec, platform, run) {
1946
+ await platform.reset(spec);
1947
+ run.install(spec.externals);
1948
+ try {
1949
+ try {
1950
+ if (!run.concurrent) await deliverInOrder(spec, platform, run);
1951
+ else if (platform.concurrent) await deliverConcurrently(spec, platform, run);
1952
+ else throw new Error(`the ${platform.name} platform delivers one event at a time`);
1953
+ } finally {
1954
+ run.uninstall();
1955
+ }
1956
+ await platform.finish?.(spec, run);
1957
+ } finally {
1958
+ await platform.cleanup?.(spec);
1959
+ }
1960
+ return run.log;
1961
+ }
1962
+ /** Re-run a recorded schedule exactly and return the whole run (log and support status). */
1963
+ async function replayRun(spec, platform, schedule) {
1964
+ const run = new Run({
1965
+ mode: "replay",
1966
+ schedule,
1967
+ bounds: spec.bounds,
1968
+ faultProbability: 0
1969
+ });
1970
+ await runOnce(spec, platform, run);
1971
+ return run;
1972
+ }
1973
+ /** Re-run a recorded schedule exactly. */
1974
+ async function replay(spec, platform, schedule) {
1975
+ return (await replayRun(spec, platform, schedule)).log;
1976
+ }
1977
+ async function explore(spec, platform, options) {
1978
+ const now = options.now ?? (() => Date.now());
1979
+ const maxRuns = options.maxRuns ?? 100;
1980
+ const faultProbability = options.faultProbability ?? .5;
1981
+ const assumptions = [
1982
+ ...engineAssumptions,
1983
+ concurrencyAssumption(spec.bounds),
1984
+ ...explorationAssumption(options),
1985
+ ...platform.assumptions
1986
+ ];
1987
+ const start = now();
1988
+ const reached = {
1989
+ runs: 0,
1990
+ effectPoints: 0,
1991
+ faultsInjected: 0
1992
+ };
1993
+ const done = () => ({
1994
+ ...reached,
1995
+ elapsedMs: now() - start
1996
+ });
1997
+ const base = {
1998
+ scenario: spec.name,
1999
+ seed: options.seed,
2000
+ assumptions
2001
+ };
2002
+ if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return {
2003
+ ...base,
2004
+ kind: "UNSUPPORTED",
2005
+ cause: "unsupported_bounds",
2006
+ reason: "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)",
2007
+ reached: done()
2008
+ };
2009
+ if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return {
2010
+ ...base,
2011
+ kind: "UNSUPPORTED",
2012
+ cause: "unsupported_bounds",
2013
+ reason: `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,
2014
+ reached: done()
2015
+ };
2016
+ const leakCheckRuns = options.leakCheckRuns ?? 2;
2017
+ /** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */
2018
+ const witnesses = [];
2019
+ let master = seedPrng(options.seed);
2020
+ let reduction = typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true;
2021
+ let enumerator = options.exhaustive ? new Enumerator({ reduction }) : null;
2022
+ let schedules = 0;
2023
+ let more = true;
2024
+ let restart = false;
2025
+ const exhaustiveReached = () => enumerator ? { exhaustive: {
2026
+ complete: !more,
2027
+ schedules,
2028
+ reduction
2029
+ } } : {};
2030
+ const doneNow = () => ({
2031
+ ...done(),
2032
+ ...exhaustiveReached()
2033
+ });
2034
+ while (more && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
2035
+ const [runSeed, next] = nextU32(master);
2036
+ master = next;
2037
+ const run = new Run({
2038
+ mode: "explore",
2039
+ schedule: {
2040
+ seed: enumerator ? 0 : runSeed,
2041
+ faults: []
2042
+ },
2043
+ bounds: spec.bounds,
2044
+ faultProbability,
2045
+ ...enumerator ? { chooser: enumerator.next() } : {}
2046
+ });
2047
+ const log = await runOnce(spec, platform, run);
2048
+ reached.runs++;
2049
+ if (enumerator) {
2050
+ if (enumerator.mismatch) return {
2051
+ ...base,
2052
+ kind: "UNSUPPORTED",
2053
+ cause: "not_replayable",
2054
+ reason: `exhaustive exploration needs deterministic runs: ${enumerator.mismatch}`,
2055
+ reached: doneNow()
2056
+ };
2057
+ restart = reduction && run.turnsMayNotCommute;
2058
+ if (!restart) {
2059
+ more = enumerator.advance();
2060
+ if (enumerator.blocked) continue;
2061
+ schedules++;
2062
+ }
2063
+ }
2064
+ reached.effectPoints += run.effectPoints;
2065
+ reached.faultsInjected += run.faultsInjected;
2066
+ if (witnesses.length < leakCheckRuns) witnesses.push({
2067
+ schedule: run.schedule,
2068
+ digest: digestLog(log)
2069
+ });
2070
+ if (run.unsupportedReasons.length > 0) return {
2071
+ ...base,
2072
+ kind: "UNSUPPORTED",
2073
+ cause: "unsupported_api",
2074
+ reason: run.unsupportedReasons.join("; "),
2075
+ reached: doneNow()
2076
+ };
2077
+ const violation = checkInvariants(log, spec.invariants)[0];
2078
+ if (violation) {
2079
+ const schedule = run.schedule;
2080
+ const replayedRun = await replayRun(spec, platform, schedule);
2081
+ const replayed = replayedRun.log;
2082
+ reached.runs++;
2083
+ if (replayedRun.unsupportedReasons.length > 0 || digestLog(replayed) !== digestLog(log)) return {
2084
+ ...base,
2085
+ kind: "UNSUPPORTED",
2086
+ cause: "not_replayable",
2087
+ reason: `the violating run of seed ${schedule.seed} did not reproduce on replay`,
2088
+ reached: doneNow()
2089
+ };
2090
+ const shrunk = await shrink(spec, platform, schedule, violation, replayed, {
2091
+ maxRuns: options.maxShrinkRuns ?? 200,
2092
+ deadline: now() + spec.bounds.budgetMs,
2093
+ now
2094
+ });
2095
+ reached.runs += shrunk.runs;
2096
+ return {
2097
+ ...base,
2098
+ kind: "VIOLATED",
2099
+ violation: shrunk.violation,
2100
+ trace: shrunk.trace,
2101
+ schedule: shrunk.schedule,
2102
+ keptEvents: shrunk.keptEvents,
2103
+ shrunk: {
2104
+ faultsRemoved: shrunk.faultsRemoved,
2105
+ eventsRemoved: shrunk.eventsRemoved,
2106
+ runs: shrunk.runs
2107
+ },
2108
+ reached: doneNow()
2109
+ };
2110
+ }
2111
+ if (restart) {
2112
+ reduction = false;
2113
+ enumerator = new Enumerator({ reduction });
2114
+ schedules = 0;
2115
+ }
2116
+ }
2117
+ for (const witness of [...witnesses].reverse()) {
2118
+ const again = await replayRun(spec, platform, witness.schedule);
2119
+ reached.runs++;
2120
+ if (again.unsupportedReasons.length > 0 || digestLog(again.log) !== witness.digest) return {
2121
+ ...base,
2122
+ kind: "UNSUPPORTED",
2123
+ cause: "module_state_leak",
2124
+ reason: `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: state is leaking between runs (module-level variables, or a binding Eutaxy does not reset)`,
2125
+ reached: doneNow()
2126
+ };
2127
+ }
2128
+ return {
2129
+ ...base,
2130
+ kind: "BOUNDED",
2131
+ bounds: spec.bounds,
2132
+ reached: doneNow()
2133
+ };
2134
+ }
2135
+ // packages/engine/src/observe.ts
2136
+ /** A JSON summary of a value for the log: exact for JSON, a readable string otherwise. */
2137
+ function summarize(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
2138
+ if (value === null || value === void 0) return null;
2139
+ switch (typeof value) {
2140
+ case "string":
2141
+ case "boolean": return value;
2142
+ case "number": return Number.isFinite(value) && !Object.is(value, -0) ? value : String(Object.is(value, -0) ? "-0" : value);
2143
+ case "bigint": return `${value}n`;
2144
+ case "function": return "[function]";
2145
+ case "symbol": return String(value);
2146
+ }
2147
+ if (depth > 8 || seen.has(value)) return "[…]";
2148
+ seen.add(value);
2149
+ try {
2150
+ if (Array.isArray(value)) return value.map((v) => summarize(v, depth + 1, seen));
2151
+ const proto = Object.getPrototypeOf(value);
2152
+ if (proto !== Object.prototype && proto !== null) return String(value);
2153
+ const out = {};
2154
+ for (const [k, v] of Object.entries(value)) Object.defineProperty(out, k, {
2155
+ value: summarize(v, depth + 1, seen),
2156
+ enumerable: true,
2157
+ writable: true,
2158
+ configurable: true
2159
+ });
2160
+ return out;
2161
+ } finally {
2162
+ seen.delete(value);
2163
+ }
2164
+ }
2165
+ function observeCore(namespace, functions) {
2166
+ const calls = [];
2167
+ const unobservable = Object.create(null);
2168
+ const undo = [];
2169
+ const target = namespace;
2170
+ for (const name of functions) {
2171
+ const original = target[name];
2172
+ if (typeof original !== "function") {
2173
+ unobservable[name] = `the module exports no function ${name}`;
2174
+ continue;
2175
+ }
2176
+ const wrapped = function(...args) {
2177
+ const run = installedRun();
2178
+ if (!run) return Reflect.apply(original, this, args);
2179
+ const record = (threw, payload) => {
2180
+ calls.push({
2181
+ function: name,
2182
+ args: [...args],
2183
+ threw
2184
+ });
2185
+ run.decision(name, {
2186
+ args: summarize(args),
2187
+ ...payload
2188
+ });
2189
+ };
2190
+ let value;
2191
+ try {
2192
+ value = Reflect.apply(original, this, args);
2193
+ } catch (err) {
2194
+ record(true, { error: String(err) });
2195
+ throw err;
2196
+ }
2197
+ if (typeof value?.then === "function") {
2198
+ run.unsupported(`core function ${name} returned a promise; observed core functions must be synchronous and pure`);
2199
+ return value;
2200
+ }
2201
+ record(false, { result: summarize(value) });
2202
+ return value;
2203
+ };
2204
+ const descriptor = Object.getOwnPropertyDescriptor(target, name);
2205
+ try {
2206
+ Object.defineProperty(target, name, {
2207
+ configurable: true,
2208
+ enumerable: descriptor?.enumerable ?? true,
2209
+ get: () => wrapped
2210
+ });
2211
+ } catch (err) {
2212
+ unobservable[name] = `its module's namespace cannot be changed here (${String(err)})`;
2213
+ continue;
2214
+ }
2215
+ if (target[name] !== wrapped) {
2216
+ unobservable[name] = "its module's namespace did not take the observer";
2217
+ continue;
2218
+ }
2219
+ undo.push(() => {
2220
+ if (descriptor) Object.defineProperty(target, name, descriptor);
2221
+ else delete target[name];
2222
+ });
2223
+ }
2224
+ let restored = false;
2225
+ return {
2226
+ calls,
2227
+ unobservable,
2228
+ restore() {
2229
+ if (restored) return;
2230
+ restored = true;
2231
+ for (const u of undo.reverse()) u();
2232
+ }
2233
+ };
2234
+ }
2235
+ export { getPath as _, CrashSignal as a, installScriptedFetch as c, realTick as d, settleOn as f, checkInvariants as g, checkInvariant as h, restrictSpec as i, withoutNetwork as l, validateScenario as m, explore as n, InjectedEffectError as o, defaultBounds as p, replay as r, Run as s, observeCore as t, patchGlobals as u };
2236
+
2237
+ //# sourceMappingURL=src-C19_yfMM.mjs.map