@typeonce/ritmo-devtools 0.13.0 → 0.15.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 (92) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/README.md +336 -58
  3. package/dist/Desync.d.ts +49 -0
  4. package/dist/Desync.d.ts.map +1 -0
  5. package/dist/Desync.js +51 -0
  6. package/dist/Desync.js.map +1 -0
  7. package/dist/Determinism.d.ts +17 -6
  8. package/dist/Determinism.d.ts.map +1 -1
  9. package/dist/Determinism.js +11 -3
  10. package/dist/Determinism.js.map +1 -1
  11. package/dist/Format.d.ts +43 -8
  12. package/dist/Format.d.ts.map +1 -1
  13. package/dist/Format.js +63 -31
  14. package/dist/Format.js.map +1 -1
  15. package/dist/Fuzz.d.ts +268 -0
  16. package/dist/Fuzz.d.ts.map +1 -0
  17. package/dist/Fuzz.js +355 -0
  18. package/dist/Fuzz.js.map +1 -0
  19. package/dist/Invariant.d.ts +6 -2
  20. package/dist/Invariant.d.ts.map +1 -1
  21. package/dist/Invariant.js.map +1 -1
  22. package/dist/Lint.d.ts +9 -3
  23. package/dist/Lint.d.ts.map +1 -1
  24. package/dist/Lint.js.map +1 -1
  25. package/dist/PlaywrightEngine.d.ts +29 -0
  26. package/dist/PlaywrightEngine.d.ts.map +1 -0
  27. package/dist/PlaywrightEngine.js +193 -0
  28. package/dist/PlaywrightEngine.js.map +1 -0
  29. package/dist/Replay.d.ts +43 -34
  30. package/dist/Replay.d.ts.map +1 -1
  31. package/dist/Replay.js +27 -33
  32. package/dist/Replay.js.map +1 -1
  33. package/dist/Session.d.ts +214 -17
  34. package/dist/Session.d.ts.map +1 -1
  35. package/dist/Session.js +563 -57
  36. package/dist/Session.js.map +1 -1
  37. package/dist/Verify.d.ts +147 -0
  38. package/dist/Verify.d.ts.map +1 -0
  39. package/dist/Verify.js +151 -0
  40. package/dist/Verify.js.map +1 -0
  41. package/dist/cli.js +136 -8
  42. package/dist/cli.js.map +1 -1
  43. package/dist/index.d.ts +4 -2
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +4 -2
  46. package/dist/index.js.map +1 -1
  47. package/dist/internal/dependencyScan.d.ts +44 -0
  48. package/dist/internal/dependencyScan.d.ts.map +1 -0
  49. package/dist/internal/dependencyScan.js +313 -0
  50. package/dist/internal/dependencyScan.js.map +1 -0
  51. package/dist/internal/fuzzNetwork.d.ts +56 -0
  52. package/dist/internal/fuzzNetwork.d.ts.map +1 -0
  53. package/dist/internal/fuzzNetwork.js +96 -0
  54. package/dist/internal/fuzzNetwork.js.map +1 -0
  55. package/dist/internal/values.d.ts +9 -1
  56. package/dist/internal/values.d.ts.map +1 -1
  57. package/dist/internal/values.js +11 -1
  58. package/dist/internal/values.js.map +1 -1
  59. package/dist/internal/verifyRunner.d.ts +19 -0
  60. package/dist/internal/verifyRunner.d.ts.map +1 -0
  61. package/dist/internal/verifyRunner.js +47 -0
  62. package/dist/internal/verifyRunner.js.map +1 -0
  63. package/dist/internal/version.d.ts +1 -1
  64. package/dist/internal/version.js +1 -1
  65. package/package.json +28 -3
  66. package/src/Desync.ts +100 -0
  67. package/src/Determinism.ts +46 -11
  68. package/src/Format.ts +99 -34
  69. package/src/Fuzz.ts +544 -0
  70. package/src/Invariant.ts +6 -2
  71. package/src/Lint.ts +9 -3
  72. package/src/PlaywrightEngine.ts +229 -0
  73. package/src/Replay.ts +98 -74
  74. package/src/Session.ts +806 -72
  75. package/src/Verify.ts +273 -0
  76. package/src/cli.ts +131 -8
  77. package/src/index.ts +4 -2
  78. package/src/internal/dependencyScan.ts +356 -0
  79. package/src/internal/fuzzNetwork.ts +130 -0
  80. package/src/internal/values.ts +20 -1
  81. package/src/internal/verifyRunner.ts +46 -0
  82. package/src/internal/version.ts +1 -1
  83. package/dist/Monitor.d.ts +0 -101
  84. package/dist/Monitor.d.ts.map +0 -1
  85. package/dist/Monitor.js +0 -602
  86. package/dist/Monitor.js.map +0 -1
  87. package/dist/internal/monitor.d.ts +0 -126
  88. package/dist/internal/monitor.d.ts.map +0 -1
  89. package/dist/internal/monitor.js +0 -279
  90. package/dist/internal/monitor.js.map +0 -1
  91. package/src/Monitor.ts +0 -713
  92. package/src/internal/monitor.ts +0 -370
package/dist/Session.js CHANGED
@@ -7,21 +7,34 @@
7
7
  * - `run(name, { frames, until })` ticks a schedule frame by frame and stops
8
8
  * at the first system failure, thrown defect, or violated invariant (an
9
9
  * invariant that throws stops it as `invariant-threw`).
10
+ * - `step(name)` begins one frame and runs it a step at a time
11
+ * (`until(System)`, `next()`, `finish()`), for a value that goes wrong
12
+ * between two systems of one frame. `journal`, `why`, and `dump` show the
13
+ * partial frame.
10
14
  * - `journal(filter)` lists what happened, one fact per line, filtered by
11
15
  * frames, entity, component, resource, event, machine, system, or kind.
12
16
  * - `why(entity, component)` lists the latest changes to one component, and
13
- * the systems whose declared `spawns` could have spawned the entity.
17
+ * the systems whose declared `spawns` could have spawned the entity. With
18
+ * `depth` above 1 it follows each change back through what the writing
19
+ * system declared it reads, one level per step (see {@link WhyOptions}).
14
20
  * - `system(name)` shows one system's declared access and recent activity.
15
21
  * - `describe()`, `dump(filter)`, `streams()` render the core debug handle.
16
22
  * - `report()` summarizes per-system timing and warnings accumulated while
17
23
  * tracing: failed systems, missed reads, commands and next states still
18
24
  * pending at the end of a frame, failed transitions, skipped systems that
19
25
  * discarded messages, sent events no system reads, NaN or infinite numbers
20
- * written anywhere, entity counts that keep growing through a run, and
26
+ * written anywhere, numbers written outside a field's declared `range`
27
+ * (the descriptor's `meta` option), entity counts that keep growing through a run, and
21
28
  * failed tick results nobody read.
22
29
  *
23
30
  * Everything returns a `Rendered` value that prints as text.
24
31
  *
32
+ * With `labels`, every entity in that text prints as `player e12` instead of
33
+ * `e12`: journal and `why` lines, `dump`, report warnings, and invariant
34
+ * messages. Labels are evaluated after every frame of a `run`, so a line
35
+ * shows the label its entity had at the end of the line's frame; an entity
36
+ * despawned by then keeps the last label it had.
37
+ *
25
38
  * @module Session
26
39
  * @docGroup devtools
27
40
  *
@@ -30,7 +43,8 @@
30
43
  * const session = Session.make(runtime, {
31
44
  * hostClock: HostClock.test(),
32
45
  * schedules: { setup: setupSchedule, update: updateSchedule },
33
- * invariants: [PlayerInsideWorld]
46
+ * invariants: [PlayerInsideWorld],
47
+ * labels: Labels
34
48
  * })
35
49
  * session.run("setup")
36
50
  * console.log(session.run("update", { frames: 300 }))
@@ -38,10 +52,12 @@
38
52
  * console.log(session.journal({ frames: [180, 185], entity: 1 }))
39
53
  * ```
40
54
  */
41
- import { HostClock } from "@typeonce/ritmo";
55
+ import { HostClock, Result } from "@typeonce/ritmo";
42
56
  import * as Format from "./Format.js";
43
57
  import * as Rendered from "./Rendered.js";
44
- import { nonFinitePath } from "./internal/values.js";
58
+ import { nonFinitePath, rangesOf } from "./internal/values.js";
59
+ /** `e12` tokens in free text (not `&e12` handles), as an invariant writes them. */
60
+ const entityToken = /(?<![\w&])e(\d+)\b/g;
45
61
  const inRange = (frame, frames) => frames === undefined ? true
46
62
  : typeof frames === "number" ? frame === frames
47
63
  : frame >= frames[0] && frame <= frames[1];
@@ -64,6 +80,15 @@ const growsSteadily = (samples) => {
64
80
  }
65
81
  return true;
66
82
  };
83
+ /** The stop for a failed tick or step result, as `run` reports it. */
84
+ const failureStop = (failure, frame) => {
85
+ const error = describeError(failure);
86
+ return error.kind === "MissingRuntimeRequirements"
87
+ ? { reason: "missingRequirements", frame, requirements: error.requirements }
88
+ : error.kind === "TickOrderViolation"
89
+ ? { reason: "tickOrder", frame, issues: (error.issues ?? []).map((issue) => issue.message) }
90
+ : { reason: "failure", frame, system: typeof error.system === "string" ? error.system : "(unknown)", error: error.error };
91
+ };
67
92
  const describeError = (error) => typeof error === "object" && error !== null ? error : {};
68
93
  /**
69
94
  * Starts a session over a runtime made with `debug: { hostClock }`: names
@@ -92,6 +117,48 @@ export const make = (runtime, options) => {
92
117
  }
93
118
  return entry;
94
119
  };
120
+ const labelsInspector = options.labels;
121
+ /** Each labelled entity's latest label; a despawned entity keeps its last one. */
122
+ const lastLabels = new Map();
123
+ /** The labels of the last evaluation. */
124
+ let latestLabels = new Map();
125
+ /** Evaluates the labels for the frame that just ended and stamps it on its record. */
126
+ const evaluateLabels = () => {
127
+ if (labelsInspector === undefined)
128
+ return;
129
+ const labels = inspect(labelsInspector);
130
+ const dropped = [...latestLabels.keys()].filter((id) => !labels.has(id));
131
+ // An entity that lost its label while alive has none now; a despawned one keeps it.
132
+ if (dropped.length > 0)
133
+ for (const alive of debug.dump({ entities: dropped }).entities)
134
+ lastLabels.delete(alive.id);
135
+ for (const [id, label] of labels)
136
+ lastLabels.set(id, label);
137
+ latestLabels = labels;
138
+ current.labels = labels;
139
+ };
140
+ /** Evaluates labels when frames ran outside `run` (queries print the latest world). */
141
+ const refreshLabels = () => {
142
+ if (labelsInspector === undefined || current.labels !== undefined)
143
+ return;
144
+ try {
145
+ evaluateLabels();
146
+ }
147
+ catch {
148
+ // A throwing labels inspector stops `run` as `labels-threw`; queries print ids alone.
149
+ }
150
+ };
151
+ /** The labels for a line of `frame`: that frame's (or the next evaluated one's), then each entity's last. */
152
+ const labelsAt = (frame) => {
153
+ if (labelsInspector === undefined)
154
+ return undefined;
155
+ const own = history.find((entry) => entry.frame >= frame && entry.labels !== undefined)?.labels;
156
+ return { get: (id) => own?.get(id) ?? lastLabels.get(id) };
157
+ };
158
+ const nowLabels = () => {
159
+ refreshLabels();
160
+ return labelsAt(debug.frame());
161
+ };
95
162
  const warnings = new Map();
96
163
  const warn = (code, key, message, frame) => {
97
164
  const existing = warnings.get(key);
@@ -123,7 +190,26 @@ export const make = (runtime, options) => {
123
190
  const path = nonFinitePath(value);
124
191
  if (path === undefined)
125
192
  return;
126
- warn("non-finite-value", `nonfinite:${system}:${subject}`, `${system} wrote a NaN or infinite number to ${entity === undefined ? "" : `e${entity} `}${subject}${path} (first at f${frame}; why() shows its history)`, frame);
193
+ warn("non-finite-value", `nonfinite:${system}:${subject}`, (labels) => `${system} wrote a NaN or infinite number to ${entity === undefined ? "" : `${Format.entity(entity, labels)} `}${subject}${path} (first at f${frame}; why() shows its history)`, frame);
194
+ };
195
+ /** The declared ranges of every component and resource field, by descriptor name, read from `describe()` on the first write. */
196
+ let ranges;
197
+ const checkRange = (kind, system, subject, value, frame, entity) => {
198
+ ranges ??= rangesOf(debug.describe());
199
+ const fields = ranges[kind].get(subject);
200
+ if (fields === undefined || typeof value !== "object" || value === null)
201
+ return;
202
+ for (const [field, min, max] of fields) {
203
+ const written = value[field];
204
+ // NaN and infinities are `non-finite-value` warnings.
205
+ if (typeof written !== "number" || !Number.isFinite(written) || (written >= min && written <= max))
206
+ continue;
207
+ warn("out-of-range", `range:${system}:${subject}.${field}`, (labels) => `${entity === undefined ? "" : `${Format.entity(entity, labels)} `}${subject}.${field} written as ${Format.value(written)}, declared range [${Format.value(min)}, ${Format.value(max)}] by ${system} at frame ${frame}`, frame);
208
+ }
209
+ };
210
+ const checkComponent = (system, subject, value, frame, entity) => {
211
+ checkFinite(system, subject, value, frame, entity);
212
+ checkRange("component", system, subject, value, frame, entity);
127
213
  };
128
214
  const record = (event) => {
129
215
  if (event.type === "frame") {
@@ -148,9 +234,11 @@ export const make = (runtime, options) => {
148
234
  if (event.commands.length > 0)
149
235
  pending.set(event.system, (pending.get(event.system) ?? 0) + event.commands.length);
150
236
  for (const write of event.writes)
151
- checkFinite(event.system, write.component, write.after, event.frame, write.entity);
152
- for (const write of event.resources)
237
+ checkComponent(event.system, write.component, write.after, event.frame, write.entity);
238
+ for (const write of event.resources) {
153
239
  checkFinite(event.system, write.resource, write.after, event.frame);
240
+ checkRange("resource", event.system, write.resource, write.after, event.frame);
241
+ }
154
242
  for (const emit of event.events)
155
243
  checkFinite(event.system, emit.event, emit.values, event.frame);
156
244
  for (const next of event.nextStates) {
@@ -191,13 +279,13 @@ export const make = (runtime, options) => {
191
279
  switch (effect.kind) {
192
280
  case "spawn":
193
281
  for (const [component, value] of Object.entries(effect.components))
194
- checkFinite(command.system, component, value, event.frame, effect.entity);
282
+ checkComponent(command.system, component, value, event.frame, effect.entity);
195
283
  break;
196
284
  case "insert":
197
- checkFinite(command.system, effect.component, effect.value, event.frame, effect.entity);
285
+ checkComponent(command.system, effect.component, effect.value, event.frame, effect.entity);
198
286
  break;
199
287
  case "overwrite":
200
- checkFinite(command.system, effect.component, effect.after, event.frame, effect.entity);
288
+ checkComponent(command.system, effect.component, effect.after, event.frame, effect.entity);
201
289
  break;
202
290
  }
203
291
  }
@@ -228,12 +316,44 @@ export const make = (runtime, options) => {
228
316
  const first = history.find((entry) => entry.events.length > 0);
229
317
  return first === undefined ? undefined : [first.frame, history[history.length - 1].frame];
230
318
  };
319
+ /** The first invariant violated (or throwing) now, in order. */
320
+ const checkInvariants = (frame) => {
321
+ for (const invariant of options.invariants ?? []) {
322
+ let message;
323
+ try {
324
+ message = inspect(invariant.inspector);
325
+ }
326
+ catch (error) {
327
+ return { reason: "invariant-threw", frame, invariant: invariant.name, error };
328
+ }
329
+ if (message !== undefined)
330
+ return { reason: "invariant", frame, invariant: invariant.name, message };
331
+ }
332
+ return undefined;
333
+ };
334
+ /** What a run compares against: taken before its first frame begins. */
335
+ const startRun = () => {
336
+ takeIgnored();
337
+ return {
338
+ started: options.hostClock.now(),
339
+ warningsBefore: new Map([...warnings].map(([key, warning]) => [key, warning.count])),
340
+ initial: debug.population()
341
+ };
342
+ };
343
+ /** The frame `session.step` has open, if any. */
344
+ let stepping;
345
+ const refuseWhileStepping = (call) => {
346
+ if (stepping !== undefined)
347
+ throw new Error(`${call} was called while frame f${stepping.frame} of ${stepping.name} is being stepped: call finish() on it first`);
348
+ };
231
349
  const run = (name, runOptions = {}) => {
350
+ refuseWhileStepping(`session.run(${name})`);
232
351
  const schedule = schedules[name];
352
+ return runFrames(name, runOptions, startRun(), () => runtime.tryTick(schedule));
353
+ };
354
+ /** Ticks `frames` frames with `tickFrame` and reports them; `run` and `finish()` share it. */
355
+ const runFrames = (name, runOptions, { started, warningsBefore, initial }, tickFrame) => {
233
356
  const frames = runOptions.frames ?? 1;
234
- const started = options.hostClock.now();
235
- const warningsBefore = new Map([...warnings].map(([key, warning]) => [key, warning.count]));
236
- const initial = debug.population();
237
357
  const entityCounts = [];
238
358
  const componentCounts = new Map(Object.keys(initial.components).map((name) => [name, []]));
239
359
  const sample = () => {
@@ -245,11 +365,10 @@ export const make = (runtime, options) => {
245
365
  let first;
246
366
  let last;
247
367
  let stop = { reason: "completed" };
248
- takeIgnored();
249
368
  for (let index = 0; index < frames; index++) {
250
369
  let result;
251
370
  try {
252
- result = runtime.tryTick(schedule);
371
+ result = tickFrame();
253
372
  }
254
373
  catch (defect) {
255
374
  const frame = debug.frame();
@@ -269,29 +388,17 @@ export const make = (runtime, options) => {
269
388
  break;
270
389
  }
271
390
  if (!result.ok) {
272
- const error = describeError(result.error);
273
- stop = error.kind === "MissingRuntimeRequirements"
274
- ? { reason: "missingRequirements", frame, requirements: error.requirements }
275
- : error.kind === "TickOrderViolation"
276
- ? { reason: "tickOrder", frame, issues: (error.issues ?? []).map((issue) => issue.message) }
277
- : { reason: "failure", frame, system: typeof error.system === "string" ? error.system : "(unknown)", error: error.error };
391
+ stop = failureStop(result.error, frame);
278
392
  break;
279
393
  }
280
- let checked;
281
- for (const invariant of options.invariants ?? []) {
282
- let message;
283
- try {
284
- message = inspect(invariant.inspector);
285
- }
286
- catch (error) {
287
- checked = { reason: "invariant-threw", frame, invariant: invariant.name, error };
288
- break;
289
- }
290
- if (message !== undefined) {
291
- checked = { reason: "invariant", frame, invariant: invariant.name, message };
292
- break;
293
- }
394
+ try {
395
+ evaluateLabels();
294
396
  }
397
+ catch (error) {
398
+ stop = { reason: "labels-threw", frame, error };
399
+ break;
400
+ }
401
+ const checked = checkInvariants(frame);
295
402
  if (checked) {
296
403
  stop = checked;
297
404
  break;
@@ -341,20 +448,165 @@ export const make = (runtime, options) => {
341
448
  const warningText = raisedCodes.length === 0
342
449
  ? ""
343
450
  : `\nwarnings during the run (see report()): ${raisedCodes.map(([code, count]) => `${code} x${count}`).join(", ")}`;
344
- return Rendered.make(data, renderRun(data, format) + lintText + warningText);
451
+ return Rendered.make(data, renderRun(data, format, labelsAt(debug.frame())) + lintText + warningText);
452
+ };
453
+ const step = (name) => {
454
+ refuseWhileStepping(`session.step(${name})`);
455
+ const schedule = schedules[name];
456
+ const start = startRun();
457
+ const begun = debug.beginFrame(schedule);
458
+ const frame = debug.frame();
459
+ const cursor = begun.ok ? begun.value : undefined;
460
+ /** Why the frame never began (missing requirements, `thisTick` order). */
461
+ const notBegun = begun.ok ? undefined : failureStop(begun.error, frame);
462
+ /** How the frame ended before `finish()`: a failed system's result, or a thrown defect. */
463
+ let ended;
464
+ let finished;
465
+ if (cursor !== undefined && cursor.remaining().length > 0)
466
+ stepping = { name, frame };
467
+ const head = notBegun === undefined ? `step ${name} f${frame}` : `step ${name}`;
468
+ const stopText = (stop) => {
469
+ switch (stop.reason) {
470
+ case "frameEnded":
471
+ return `${head}: the frame has ended; finish() reports it`;
472
+ case "notAhead":
473
+ return `${head}: ${stop.system} is not ahead (it already ran this frame, or ${name} does not run it as a step); nothing ran. Remaining: ${stop.remaining.length === 0 ? "(none)" : stop.remaining.map(Format.step).join(", ")}`;
474
+ case "failure":
475
+ return `${head}: ${stop.system} FAILED: ${Format.value(stop.error, format)}; the frame ended, finish() reports it`;
476
+ case "defect":
477
+ return `${head}: DEFECT: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`;
478
+ case "missingRequirements":
479
+ return `${head}: NOT BEGUN: missing runtime requirements ${Format.value(stop.requirements, format)}`;
480
+ case "tickOrder":
481
+ return `${head}: NOT BEGUN: ${stop.issues.join("; ")}`;
482
+ }
483
+ };
484
+ const remainingSteps = () => cursor === undefined || ended !== undefined ? [] : cursor.remaining();
485
+ const nextText = () => {
486
+ const left = remainingSteps();
487
+ return left.length === 0 ? "the frame ended, finish() reports it" : `next: ${Format.step(left[0])}`;
488
+ };
489
+ const unavailable = () => notBegun ?? (remainingSteps().length === 0 ? { reason: "frameEnded", frame } : undefined);
490
+ /** Runs one step; a failure or defect ends the frame. */
491
+ const advance = () => {
492
+ const stop = unavailable();
493
+ if (stop !== undefined)
494
+ return Result.failure(stop);
495
+ let result;
496
+ try {
497
+ result = cursor.next();
498
+ }
499
+ catch (defect) {
500
+ ended = { defect };
501
+ stepping = undefined;
502
+ return Result.failure({ reason: "defect", frame, error: defect });
503
+ }
504
+ finally {
505
+ // Labels evaluated mid-frame are evaluated again for the world after this step.
506
+ if (current.frame === frame)
507
+ delete current.labels;
508
+ }
509
+ if (!result.ok) {
510
+ ended = { result: Result.failure(result.error) };
511
+ stepping = undefined;
512
+ return Result.failure(failureStop(result.error, frame));
513
+ }
514
+ if (result.value.ended)
515
+ stepping = undefined;
516
+ return Result.success(result.value);
517
+ };
518
+ const stepped = {
519
+ until: (system) => {
520
+ const unavailableStop = unavailable();
521
+ const left = remainingSteps();
522
+ const offset = schedule.steps
523
+ .slice(schedule.steps.length - left.length)
524
+ .findIndex((entry) => "ordering" in entry && entry.ordering.key === system.ordering.key);
525
+ const stop = unavailableStop
526
+ ?? (offset === -1 ? { reason: "notAhead", frame, system: system.name, remaining: left } : undefined);
527
+ if (stop !== undefined)
528
+ return Rendered.make(Result.failure(stop), stopText(stop));
529
+ const ran = [];
530
+ for (let index = 0; index < offset; index++) {
531
+ const result = advance();
532
+ if (!result.ok)
533
+ return Rendered.make(Result.failure(result.error), stopText(result.error));
534
+ ran.push(result.value.step);
535
+ }
536
+ const reached = { frame, system: system.name, ran };
537
+ return Rendered.make(Result.success(reached), `${head}: stopped before ${system.name}; ${ran.length === 0 ? "nothing ran" : `ran ${ran.map(Format.step).join(", ")}`}`);
538
+ },
539
+ next: () => {
540
+ const result = advance();
541
+ if (!result.ok)
542
+ return Rendered.make(Result.failure(result.error), stopText(result.error));
543
+ const ran = { frame, step: result.value.step, ended: result.value.ended };
544
+ return Rendered.make(Result.success(ran), `${head}: ran ${Format.step(ran.step)}; ${nextText()}`);
545
+ },
546
+ remaining: () => {
547
+ const left = remainingSteps();
548
+ return Rendered.make(left, left.length === 0
549
+ ? `${head}: no steps left; ${finished === undefined ? "finish() reports the frame" : "finished"}`
550
+ : `${head}: ${left.length} steps left: ${left.map(Format.step).join(", ")}`);
551
+ },
552
+ check: () => {
553
+ const at = remainingSteps();
554
+ const where = at.length === 0 ? "at the end of the frame" : `before ${Format.step(at[0])}`;
555
+ const stop = checkInvariants(frame);
556
+ if (stop === undefined)
557
+ return Rendered.make(Result.success(undefined), `${head}: invariants hold ${where}`);
558
+ const text = stop.reason === "invariant"
559
+ ? `${head}: INVARIANT "${stop.invariant}" violated ${where}: ${stop.message.replace(entityToken, (_token, id) => Format.entity(Number(id), nowLabels()))} (it may hold again by the end of the frame)`
560
+ : `${head}: INVARIANT "${stop.invariant}" threw ${where}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`;
561
+ return Rendered.make(Result.failure(stop), text);
562
+ },
563
+ finish: () => {
564
+ finished ??= runFrames(name, {}, start, () => {
565
+ if (!begun.ok)
566
+ return begun;
567
+ if (ended !== undefined) {
568
+ if ("defect" in ended)
569
+ throw ended.defect;
570
+ return ended.result;
571
+ }
572
+ try {
573
+ while (cursor.remaining().length > 0) {
574
+ const result = cursor.next();
575
+ if (!result.ok)
576
+ return result;
577
+ }
578
+ return Result.success(undefined);
579
+ }
580
+ finally {
581
+ stepping = undefined;
582
+ }
583
+ });
584
+ return finished;
585
+ }
586
+ };
587
+ return stepped;
345
588
  };
346
589
  /** Lines hidden by the last `collectLines` call because they record no change. */
347
590
  let hidden = 0;
348
- const collectLines = (filter) => {
591
+ const collectLines = (filter) => collectSourced(filter).map((entry) => entry.line);
592
+ /** The journal lines of `filter`, each with its event's position in {@link flatTrace}. */
593
+ const collectSourced = (filter) => {
349
594
  hidden = 0;
595
+ refreshLabels();
350
596
  const subject = filter.component?.name ?? filter.resource?.name ?? filter.event?.name ?? filter.machine?.name;
351
- const records = filter.last === undefined ? history : history.slice(-filter.last);
597
+ // `slice(-last)` keeps the journal's meaning of `last` (0 keeps everything).
598
+ const first = filter.last === undefined ? 0 : history.length - history.slice(-filter.last).length;
352
599
  const result = [];
353
- for (const entry of records) {
354
- if (!inRange(entry.frame, filter.frames))
600
+ let at = 0;
601
+ for (const [index, entry] of history.entries()) {
602
+ if (index < first || !inRange(entry.frame, filter.frames)) {
603
+ at += entry.events.length;
355
604
  continue;
605
+ }
606
+ const labels = labelsAt(entry.frame);
356
607
  for (const event of entry.events) {
357
- for (const line of Format.lines(event, format)) {
608
+ const position = at++;
609
+ for (const line of Format.lines(event, format, labels)) {
358
610
  if (filter.entity !== undefined && line.entity !== filter.entity)
359
611
  continue;
360
612
  if (subject !== undefined && line.subject !== subject && !(line.kind === "effect" && line.subject === undefined && filter.entity !== undefined))
@@ -369,7 +621,7 @@ export const make = (runtime, options) => {
369
621
  hidden += 1;
370
622
  continue;
371
623
  }
372
- result.push(line);
624
+ result.push({ line, at: position });
373
625
  }
374
626
  }
375
627
  }
@@ -386,20 +638,22 @@ export const make = (runtime, options) => {
386
638
  return Rendered.make(lines, renderLines(`journal: ${lines.length} lines (${rangeText()}${hiddenText})`, lines));
387
639
  };
388
640
  const why = (entity, component, whyOptions = {}) => {
389
- const lines = collectLines({ entity, component, kinds: ["write", "effect"], limit: whyOptions.limit ?? 5 });
641
+ const sourced = collectSourced({ entity, component, kinds: ["write", "effect"], limit: whyOptions.limit ?? 5 });
642
+ const lines = followReads(sourced, whyOptions);
390
643
  const currentValue = debug.dump({ entities: [entity] }).entities[0];
644
+ const name = Format.entity(entity, nowLabels());
391
645
  const now = currentValue === undefined
392
- ? `e${entity} is not alive`
646
+ ? `${name} is not alive`
393
647
  : component.name in currentValue.components
394
- ? `e${entity} ${component.name} is now ${Format.value(currentValue.components[component.name], format)}`
395
- : `e${entity} has no ${component.name} now`;
396
- const changes = lines.length === 0
648
+ ? `${name} ${component.name} is now ${Format.value(currentValue.components[component.name], format)}`
649
+ : `${name} has no ${component.name} now`;
650
+ const changes = sourced.length === 0
397
651
  ? `${now}; no change to it in ${rangeText()}`
398
- : `${now}; last ${lines.length} changes (oldest first):`;
652
+ : `${now}; last ${sourced.length} changes (oldest first):`;
399
653
  const spawners = spawnersOf(currentValue === undefined ? [component.name] : Object.keys(currentValue.components), component.name);
400
654
  const header = `${changes}\n${spawners.length === 0
401
655
  ? `no described system declares spawns of ${component.name}`
402
- : `could have spawned it: ${spawners.join(", ")}`}`;
656
+ : `could have spawned it: ${spawners.join(", ")}`}${readsNote(lines)}`;
403
657
  return Rendered.make(lines, renderLines(header, lines));
404
658
  };
405
659
  /**
@@ -416,16 +670,262 @@ export const make = (runtime, options) => {
416
670
  .map((system) => system.name);
417
671
  };
418
672
  const whyResource = (resource, whyOptions = {}) => {
419
- const lines = collectLines({ resource, kinds: ["resource"], limit: whyOptions.limit ?? 5 });
673
+ const lines = followReads(collectSourced({ resource, kinds: ["resource"], limit: whyOptions.limit ?? 5 }), whyOptions);
420
674
  const resources = debug.dump({ limit: 0 }).resources;
421
675
  const now = resource.name in resources
422
676
  ? `${resource.name} is now ${Format.value(resources[resource.name], format)}`
423
677
  : `${resource.name} has no value now`;
424
- const header = lines.length === 0
678
+ const changes = lines.filter((line) => line.depth === 0).length;
679
+ const header = changes === 0
425
680
  ? `${now}; no change to it in ${rangeText()}`
426
- : `${now}; last ${lines.length} changes (oldest first):`;
681
+ : `${now}; last ${changes} changes (oldest first):${readsNote(lines)}`;
427
682
  return Rendered.make(lines, renderLines(header, lines));
428
683
  };
684
+ /** The header note `why` adds when it printed declared reads. */
685
+ const readsNote = (lines) => lines.some((line) => line.depth > 0)
686
+ ? "\nindented: what each writing system declared it reads, and the latest fact that could have produced it (declared: possible causes, not observed reads)"
687
+ : "";
688
+ /** Every kept trace event, oldest first; {@link collectSourced} positions index into it. */
689
+ const flatTrace = () => history.flatMap((entry) => entry.events);
690
+ /**
691
+ * The changes `why` lists, each followed (with `depth` above 1) by the
692
+ * reads its system declared, depth first. Positions are in trace order, so
693
+ * "before the run" is what the system could have seen.
694
+ */
695
+ const followReads = (sourced, whyOptions) => {
696
+ const depth = whyOptions.depth ?? 1;
697
+ const limit = whyOptions.limit ?? 5;
698
+ if (depth <= 1 || sourced.length === 0)
699
+ return sourced.map((entry) => entry.line);
700
+ const trace = flatTrace();
701
+ const systems = new Map(debug.describe().systems.map((entry) => [entry.name, entry]));
702
+ let world;
703
+ const worldNow = () => (world ??= debug.dump().entities);
704
+ /** The latest committed run of `system` before `before`. */
705
+ const runBefore = (system, before) => {
706
+ for (let at = before - 1; at >= 0; at--) {
707
+ const event = trace[at];
708
+ if (event.type === "system" && event.system === system && event.outcome === "ok")
709
+ return { at, run: event };
710
+ }
711
+ return undefined;
712
+ };
713
+ /** Where the stream reads of the run at `at` start: after the system's previous run, or the discarding skip. */
714
+ const readsSince = (system, at) => {
715
+ for (let index = at - 1; index >= 0; index--) {
716
+ const event = trace[index];
717
+ if ((event.type === "system" && event.system === system) || (event.type === "system.skipped" && event.system === system && !event.held))
718
+ return index + 1;
719
+ }
720
+ return 0;
721
+ };
722
+ const latest = (before, find) => {
723
+ for (let at = before - 1; at >= 0; at--) {
724
+ const found = find(trace[at], at);
725
+ if (found !== undefined)
726
+ return found;
727
+ }
728
+ return undefined;
729
+ };
730
+ const readsOf = (cause) => {
731
+ const { run } = cause;
732
+ const description = systems.get(run.system);
733
+ const here = { frame: run.frame, schedule: run.schedule, system: undefined, entity: undefined, next: undefined };
734
+ if (description === undefined) {
735
+ return [{ ...here, subject: run.system, text: `${run.system} is in no named or described schedule: its declared reads are unknown` }];
736
+ }
737
+ const reads = [];
738
+ const since = readsSince(run.system, cause.at);
739
+ for (const name of description.events.reads) {
740
+ const before = reads.length;
741
+ for (let at = since; at < cause.at; at++) {
742
+ const event = trace[at];
743
+ if (event.type === "runtime.sent" && event.event === name) {
744
+ reads.push({ ...here, frame: event.frame, schedule: "", subject: name, text: `read ${name} ${Format.value([event.value], format)} (declared), sent by runtime.send at f${event.frame}` });
745
+ }
746
+ if (event.type === "system" && event.outcome === "ok") {
747
+ for (const emitted of event.events) {
748
+ if (emitted.event !== name)
749
+ continue;
750
+ reads.push({
751
+ frame: event.frame,
752
+ schedule: event.schedule,
753
+ system: event.system,
754
+ entity: undefined,
755
+ subject: name,
756
+ text: `read ${name} ${Format.value(emitted.values, format)} (declared), emitted by ${event.system} at f${event.frame}`,
757
+ next: { at, run: event, entity: undefined, subject: undefined }
758
+ });
759
+ }
760
+ }
761
+ }
762
+ if (reads.length === before) {
763
+ reads.push({ ...here, subject: name, text: `read ${name} (declared): nothing published to it since ${run.system}'s previous run` });
764
+ }
765
+ }
766
+ for (const query of description.queries) {
767
+ const components = [...query.reads, ...query.writes, ...query.optional];
768
+ if (cause.entity !== undefined && cause.subject !== undefined && query.writes.includes(cause.subject)) {
769
+ const entity = cause.entity;
770
+ for (const name of components.filter((component) => component !== cause.subject)) {
771
+ reads.push(componentRead(cause, entity, name));
772
+ }
773
+ }
774
+ else if (components.length > 0) {
775
+ const required = [...query.reads, ...query.writes, ...query.with];
776
+ const count = worldNow().filter((dumped) => required.every((name) => name in dumped.components) && !query.without.some((name) => name in dumped.components)).length;
777
+ reads.push({
778
+ ...here,
779
+ subject: components[0],
780
+ text: `read ${components.join(", ")} of ${count} matching ${count === 1 ? "entity" : "entities"} now (declared; the trace does not say which it read)`
781
+ });
782
+ }
783
+ }
784
+ for (const name of new Set([...description.resources.reads, ...description.resources.writes])) {
785
+ if (name === cause.subject && cause.entity === undefined)
786
+ continue;
787
+ const found = latest(cause.at, (event, at) => {
788
+ if (event.type !== "system" || event.outcome !== "ok")
789
+ return undefined;
790
+ // An equal-value write did not produce the value; the change before it did.
791
+ const write = event.resources.find((entry) => entry.resource === name && !Format.sameValue(entry.before, entry.after));
792
+ return write === undefined ? undefined : { at, event, write };
793
+ });
794
+ reads.push(found === undefined
795
+ ? { ...here, subject: name, text: `read resource ${name} (declared): no change to it in ${rangeText()}` }
796
+ : {
797
+ frame: found.event.frame,
798
+ schedule: found.event.schedule,
799
+ system: found.event.system,
800
+ entity: undefined,
801
+ subject: name,
802
+ text: `read resource ${name} ${Format.value(found.write.after, format)} (declared), written by ${found.event.system} at f${found.event.frame}`,
803
+ next: { at: found.at, run: found.event, entity: undefined, subject: name }
804
+ });
805
+ }
806
+ for (const name of new Set([...description.machines.reads, ...description.machines.updates])) {
807
+ const found = latest(cause.at, (event, at) => {
808
+ if (event.type === "transition" && event.machine === name && (event.outcome === "applied" || event.outcome === "enterFailed")) {
809
+ return { ...here, frame: event.frame, schedule: event.schedule, subject: name, text: `read machine ${name} (declared): transition ${Format.transition(event)} ${event.outcome} at f${event.frame}` };
810
+ }
811
+ if (event.type !== "system" || event.outcome !== "ok" || event.system === run.system)
812
+ return undefined;
813
+ const write = event.machines.find((entry) => entry.machine === name);
814
+ return write === undefined ? undefined : {
815
+ frame: event.frame,
816
+ schedule: event.schedule,
817
+ system: event.system,
818
+ entity: undefined,
819
+ subject: name,
820
+ text: `read machine ${name} ${Format.change(write.before, write.after, format)} (declared), updated by ${event.system} at f${event.frame}`,
821
+ next: { at, run: event, entity: undefined, subject: undefined }
822
+ };
823
+ });
824
+ reads.push(found ?? { ...here, subject: name, text: `read machine ${name} (declared): no transition in ${rangeText()}` });
825
+ }
826
+ if (reads.length === 0)
827
+ reads.push({ ...here, subject: run.system, text: `${run.system} declares no other reads (declared)` });
828
+ return reads;
829
+ };
830
+ /** The latest value of `component` on `entity` before the cause's run, and what produced it. */
831
+ const componentRead = (cause, entity, component) => {
832
+ const name = Format.entity(entity, labelsAt(cause.run.frame));
833
+ const found = latest(cause.at, (event, at) => {
834
+ if (event.type === "system" && event.outcome === "ok") {
835
+ const write = event.writes.find((entry) => entry.entity === entity && entry.component === component && !Format.sameValue(entry.before, entry.after));
836
+ return write === undefined ? undefined : {
837
+ frame: event.frame,
838
+ schedule: event.schedule,
839
+ system: event.system,
840
+ entity,
841
+ subject: component,
842
+ text: `read ${name} ${component} ${Format.value(write.after, format)} (declared), written by ${event.system} at f${event.frame}`,
843
+ next: { at, run: event, entity, subject: component }
844
+ };
845
+ }
846
+ if (event.type !== "deferred")
847
+ return undefined;
848
+ for (const command of [...event.commands].reverse()) {
849
+ for (const effect of [...command.effects].reverse()) {
850
+ if (effect.entity !== entity)
851
+ continue;
852
+ const value = effect.kind === "spawn" ? (component in effect.components ? { found: effect.components[component] } : undefined)
853
+ : effect.kind === "insert" && effect.component === component ? { found: effect.value }
854
+ : effect.kind === "overwrite" && effect.component === component ? { found: effect.after }
855
+ : undefined;
856
+ if (value === undefined)
857
+ continue;
858
+ const queued = runBefore(command.system, at);
859
+ return {
860
+ frame: event.frame,
861
+ schedule: event.schedule,
862
+ system: command.system,
863
+ entity,
864
+ subject: component,
865
+ text: `read ${name} ${component} ${Format.value(value.found, format)} (declared), ${effect.kind === "spawn" ? "spawned" : "inserted"} by ${command.system} at f${event.frame}`,
866
+ next: queued === undefined ? undefined : { ...queued, entity: undefined, subject: undefined }
867
+ };
868
+ }
869
+ }
870
+ return undefined;
871
+ });
872
+ return found ?? { frame: cause.run.frame, schedule: cause.run.schedule, system: undefined, entity, subject: component, text: `read ${name} ${component} (declared): no change to it in ${rangeText()}`, next: undefined };
873
+ };
874
+ const toLine = (read, level, suffix) => {
875
+ const label = read.entity === undefined ? undefined : labelsAt(read.frame)?.get(read.entity);
876
+ return {
877
+ kind: "read",
878
+ frame: read.frame,
879
+ schedule: read.schedule,
880
+ system: read.system,
881
+ entity: read.entity,
882
+ label: label === "" ? undefined : label,
883
+ subject: read.subject,
884
+ text: `${read.text}${suffix}`,
885
+ noop: false,
886
+ depth: level
887
+ };
888
+ };
889
+ const out = [];
890
+ const follow = (cause, level, chain) => {
891
+ const reads = readsOf(cause);
892
+ for (const read of reads.slice(0, limit)) {
893
+ const cycle = read.next !== undefined && chain.has(read.next.run.system);
894
+ out.push(toLine(read, level, cycle ? " (cycle: not followed)" : ""));
895
+ if (read.next !== undefined && !cycle && level + 1 < depth)
896
+ follow(read.next, level + 1, new Set([...chain, read.next.run.system]));
897
+ }
898
+ if (reads.length > limit) {
899
+ out.push({
900
+ kind: "read",
901
+ frame: cause.run.frame,
902
+ schedule: cause.run.schedule,
903
+ system: undefined,
904
+ entity: undefined,
905
+ label: undefined,
906
+ subject: undefined,
907
+ text: `…+${reads.length - limit} more declared reads of ${cause.run.system} (raise limit to see them)`,
908
+ noop: false,
909
+ depth: level
910
+ });
911
+ }
912
+ };
913
+ /** The run behind a listed change: the writing run, or for an applied command the run that queued it. */
914
+ const causeOf = (line, at) => {
915
+ const event = trace[at];
916
+ if (event?.type === "system")
917
+ return { at, run: event, entity: line.entity, subject: line.subject };
918
+ const queued = event?.type === "deferred" && line.system !== undefined ? runBefore(line.system, at) : undefined;
919
+ return queued === undefined ? undefined : { ...queued, entity: undefined, subject: undefined };
920
+ };
921
+ for (const { line, at } of sourced) {
922
+ out.push(line);
923
+ const cause = causeOf(line, at);
924
+ if (cause !== undefined)
925
+ follow(cause, 1, new Set([cause.run.system]));
926
+ }
927
+ return out;
928
+ };
429
929
  const statsFor = (system) => {
430
930
  const entry = stats.get(system);
431
931
  return entry === undefined ? undefined : { system, ...entry };
@@ -457,7 +957,10 @@ export const make = (runtime, options) => {
457
957
  frames: debug.frame(),
458
958
  history: historyRange(),
459
959
  systems,
460
- warnings: [...warnings.values()].map((warning) => ({ ...warning })),
960
+ warnings: [...warnings.values()].map((warning) => ({
961
+ ...warning,
962
+ message: typeof warning.message === "string" ? warning.message : warning.message(labelsAt(warning.firstFrame))
963
+ })),
461
964
  streams: debug.streams().filter((stream) => stream.heldBy !== undefined || stream.readers.some((reader) => reader.lagged)),
462
965
  lints: debug.describe().lints,
463
966
  population: debug.population()
@@ -481,6 +984,7 @@ export const make = (runtime, options) => {
481
984
  };
482
985
  return {
483
986
  run,
987
+ step: step,
484
988
  journal,
485
989
  why,
486
990
  whyResource,
@@ -491,7 +995,7 @@ export const make = (runtime, options) => {
491
995
  },
492
996
  dump: (filter) => {
493
997
  const dumped = debug.dump(filter);
494
- return Rendered.make(dumped, Format.dump(dumped, format));
998
+ return Rendered.make(dumped, Format.dump(dumped, format, nowLabels()));
495
999
  },
496
1000
  streams: () => {
497
1001
  const status = debug.streams();
@@ -505,7 +1009,7 @@ export const make = (runtime, options) => {
505
1009
  }
506
1010
  };
507
1011
  };
508
- const renderRun = (result, format) => {
1012
+ const renderRun = (result, format, labels) => {
509
1013
  const frames = result.range === undefined ? "no frames" : `f${result.range[0]}-f${result.range[1]}`;
510
1014
  const head = `run ${result.schedule}: ${result.frames} frames (${frames}) in ${Format.value(result.ms)}ms`;
511
1015
  const stop = result.stop;
@@ -521,9 +1025,11 @@ const renderRun = (result, format) => {
521
1025
  case "defect":
522
1026
  return `${head}, DEFECT at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`;
523
1027
  case "invariant":
524
- return `${head}, INVARIANT "${stop.invariant}" violated at f${stop.frame}: ${stop.message}`;
1028
+ return `${head}, INVARIANT "${stop.invariant}" violated at f${stop.frame}: ${stop.message.replace(entityToken, (_token, id) => Format.entity(Number(id), labels))}`;
525
1029
  case "invariant-threw":
526
1030
  return `${head}, INVARIANT "${stop.invariant}" threw at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`;
1031
+ case "labels-threw":
1032
+ return `${head}, LABELS threw at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`;
527
1033
  case "tickOrder":
528
1034
  return `${head}, NOT RUN after f${stop.frame}: ${stop.issues.join("; ")}`;
529
1035
  case "ignored-failure":