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