@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/src/Desync.ts CHANGED
@@ -5,19 +5,27 @@
5
5
  * A `Netcode` session made with `keepSnapshots: true` fails with `Desynced`
6
6
  * carrying this peer's save of the tick whose checksums differ; the other
7
7
  * peer's session carries its own. `compare(mine, theirs)` lists every
8
- * difference, entities by id and values by path, so an agent can see which
8
+ * difference, entities by id (and label, given `labels`) and values by path, so an agent can see which
9
9
  * component or resource went apart first, then find the system that wrote
10
10
  * it with a `Session`'s `why` on a headless rerun.
11
+ * The same goes for the two saves a `Netcode.syncTest`'s `RewindDiffers`
12
+ * carries (`keepSnapshots: true`): the first run's and the one after a rewind.
11
13
  *
12
14
  * @module Desync
13
15
  * @docGroup devtools
14
16
  *
15
17
  * @example
16
18
  * ```ts
19
+ * declare const sessions: readonly [Netcode.Session<{ dx: number }, unknown>, Netcode.Session<{ dx: number }, unknown>]
20
+ * declare const input: { dx: number }
21
+ * const Labels = Game.Inspector("labels", {
22
+ * queries: { players: Game.Query({ selection: { position: Game.Query.read(Position) }, with: [Player] }) }
23
+ * }, ({ queries }) => new Map(queries.players.each().map((match) => [match.entity.id, "player"] as const)))
24
+ * // ---cut---
17
25
  * const left = sessions[0].advance(input)
18
26
  * const right = sessions[1].advance(input)
19
27
  * if (!left.ok && left.error._tag === "Desynced" && !right.ok && right.error._tag === "Desynced") {
20
- * console.log(Desync.compare(left.error.snapshot!, right.error.snapshot!))
28
+ * console.log(Desync.compare(left.error.snapshot!, right.error.snapshot!, { labels: runtime.inspect(Labels) }))
21
29
  * }
22
30
  * ```
23
31
  */
@@ -30,6 +38,8 @@ import * as Rendered from "./Rendered.ts"
30
38
  export interface Difference {
31
39
  /** `nextEntity`, `entity 12`, `entity 12 Game/Position.x`, `resource Game/Score`, `machine Game/Round`, `relation Game/ChildOf`, or `scope Game/Wave`. */
32
40
  readonly path: string
41
+ /** The entity the difference is in, when it is in one. */
42
+ readonly entity: number | undefined
33
43
  readonly mine: unknown
34
44
  readonly theirs: unknown
35
45
  }
@@ -38,46 +48,59 @@ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
38
48
  typeof value === "object" && value !== null && !Array.isArray(value)
39
49
 
40
50
  /** The leaves where two values differ, under `path`. */
41
- const differences = (path: string, mine: unknown, theirs: unknown, into: Array<Difference>): void => {
51
+ const differences = (path: string, entity: number | undefined, mine: unknown, theirs: unknown, into: Array<Difference>): void => {
42
52
  if (Format.sameValue(mine, theirs)) return
43
53
  if (isRecord(mine) && isRecord(theirs)) {
44
54
  for (const key of [...new Set([...Object.keys(mine), ...Object.keys(theirs)])].sort()) {
45
- differences(`${path}.${key}`, mine[key], theirs[key], into)
55
+ differences(`${path}.${key}`, entity, mine[key], theirs[key], into)
46
56
  }
47
57
  return
48
58
  }
49
59
  if (Array.isArray(mine) && Array.isArray(theirs) && mine.length === theirs.length) {
50
- mine.forEach((item, index) => differences(`${path}[${index}]`, item, theirs[index], into))
60
+ mine.forEach((item, index) => differences(`${path}[${index}]`, entity, item, theirs[index], into))
51
61
  return
52
62
  }
53
- into.push({ path, mine, theirs })
63
+ into.push({ path, entity, mine, theirs })
54
64
  }
55
65
 
56
66
  /** Each named entry of two records, compared under `kind name`. */
57
- const byName = (kind: string, mine: Readonly<Record<string, unknown>>, theirs: Readonly<Record<string, unknown>>, into: Array<Difference>): void => {
67
+ const byName = (kind: string, entity: number | undefined, mine: Readonly<Record<string, unknown>>, theirs: Readonly<Record<string, unknown>>, into: Array<Difference>): void => {
58
68
  for (const name of [...new Set([...Object.keys(mine), ...Object.keys(theirs)])].sort()) {
59
- differences(`${kind} ${name}`, mine[name], theirs[name], into)
69
+ differences(`${kind} ${name}`, entity, mine[name], theirs[name], into)
60
70
  }
61
71
  }
62
72
 
73
+ /** How `compare` prints. */
74
+ export interface CompareOptions {
75
+ /**
76
+ * Names entities in the text (`player e12 Game/Position.x`): the map the
77
+ * session's `labels` inspector returns, read with `runtime.inspect(Labels)`
78
+ * on either peer. Without it entities print as `e12`.
79
+ */
80
+ readonly labels?: Format.Labels
81
+ }
82
+
63
83
  /** Every difference between two saves, in a stable order: the next id, entities by id, then resources, machines, relations, and scopes by name. */
64
- export const compare = (mine: Snapshot.WorldSnapshot, theirs: Snapshot.WorldSnapshot): Rendered.Rendered<ReadonlyArray<Difference>> => {
84
+ export const compare = (mine: Snapshot.WorldSnapshot, theirs: Snapshot.WorldSnapshot, options: CompareOptions = {}): Rendered.Rendered<ReadonlyArray<Difference>> => {
65
85
  const found: Array<Difference> = []
66
- differences("nextEntity", mine.nextEntity, theirs.nextEntity, found)
86
+ differences("nextEntity", undefined, mine.nextEntity, theirs.nextEntity, found)
67
87
  const mineById = new Map(mine.entities.map((entity) => [entity.id, entity.components] as const))
68
88
  const theirsById = new Map(theirs.entities.map((entity) => [entity.id, entity.components] as const))
69
89
  for (const id of [...new Set([...mineById.keys(), ...theirsById.keys()])].sort((a, b) => a - b)) {
70
90
  const left = mineById.get(id)
71
91
  const right = theirsById.get(id)
72
- if (left === undefined || right === undefined) found.push({ path: `entity ${id}`, mine: left, theirs: right })
73
- else byName(`entity ${id}`, left, right, found)
92
+ if (left === undefined || right === undefined) found.push({ path: `entity ${id}`, entity: id, mine: left, theirs: right })
93
+ else byName(`entity ${id}`, id, left, right, found)
74
94
  }
75
- byName("resource", mine.resources, theirs.resources, found)
76
- byName("machine", mine.machines, theirs.machines, found)
77
- byName("relation", mine.relations, theirs.relations, found)
78
- byName("scope", mine.scopes, theirs.scopes, found)
95
+ byName("resource", undefined, mine.resources, theirs.resources, found)
96
+ byName("machine", undefined, mine.machines, theirs.machines, found)
97
+ byName("relation", undefined, mine.relations, theirs.relations, found)
98
+ byName("scope", undefined, mine.scopes, theirs.scopes, found)
99
+ // `entity 12 ...` prints as `player e12 ...`, like every entity in devtools text.
100
+ const where = ({ path, entity }: Difference) =>
101
+ entity === undefined ? path : `${Format.entity(entity, options.labels)}${path.slice(`entity ${entity}`.length)}`
79
102
  const text = found.length === 0
80
103
  ? "The saves are equal."
81
- : [`${found.length} difference${found.length === 1 ? "" : "s"} (mine -> theirs):`, ...found.map(({ path, mine, theirs }) => ` ${path}: ${Format.value(mine)} -> ${Format.value(theirs)}`)].join("\n")
104
+ : [`${found.length} difference${found.length === 1 ? "" : "s"} (mine -> theirs):`, ...found.map((difference) => ` ${where(difference)}: ${Format.value(difference.mine)} -> ${Format.value(difference.theirs)}`)].join("\n")
82
105
  return Rendered.make(found, text)
83
106
  }
@@ -8,10 +8,18 @@
8
8
  * system or schedule marker after which the worlds differ. If that rerun
9
9
  * does not reproduce it, `after` is undefined: the original mismatch still
10
10
  * fails the check. This checks repeatability on the current JS engine, not
11
- * equality between platforms or every possible input sequence.
11
+ * equality between platforms (`Verify.acrossEngines` plays a replay in real
12
+ * browsers for that) or every possible input sequence.
13
+ *
14
+ * A difference inside an entity names it (`entity`), and with `labels` (the
15
+ * session's labels inspector) also its label, read on the first world at the
16
+ * differing frame.
12
17
  *
13
18
  * @example
14
19
  * ```ts
20
+ * // The game's factory: a fresh runtime on the given host clock each call.
21
+ * declare const makeSimulation: (hostClock: HostClock.HostClock) => Replay.Target<typeof Game.schema, typeof Root>
22
+ * // ---cut---
15
23
  * const result = Determinism.check(({ hostClock }) => makeSimulation(hostClock), {
16
24
  * schedule: "update", frames: 1800, hostClock: HostClock.test()
17
25
  * })
@@ -21,13 +29,21 @@
21
29
  * @docGroup devtools
22
30
  */
23
31
  import type { Debug, HostClock } from "@typeonce/ritmo"
32
+ import type * as Inspector from "@typeonce/ritmo/Inspector"
24
33
  import type { Schema } from "@typeonce/ritmo/Schema"
25
34
  import type { AnyScheduleOrder, ExecutableScheduleDefinition } from "@typeonce/ritmo/Schedule"
26
- import type { Target as SessionTarget } from "./Session.ts"
35
+ import type { LabelsInspector, Target as SessionTarget, ValidateLabels } from "./Session.ts"
27
36
 
28
37
  /** A fresh debug runtime, already set up, and its runnable schedules. */
29
- export interface Target<S extends Schema.Any, Root, Names extends string> {
30
- readonly runtime: Pick<SessionTarget<S, Root>, "debug" | "tryTick">
38
+ export interface Target<
39
+ S extends Schema.Any,
40
+ Root,
41
+ Names extends string,
42
+ Services extends Record<string, unknown> = Record<string, unknown>,
43
+ Resources extends object = object,
44
+ Machines extends Record<string, unknown> = Record<string, unknown>
45
+ > {
46
+ readonly runtime: SessionTarget<S, Root, Services, Resources, Machines>
31
47
  readonly schedules: Readonly<Record<Names, ExecutableScheduleDefinition<S, any, Root, any, any, AnyScheduleOrder>>>
32
48
  }
33
49
 
@@ -37,9 +53,11 @@ export interface Context {
37
53
  }
38
54
 
39
55
  /** Selects one schedule and a finite, whole number of frames to compare. */
40
- export interface Options<Names extends string> extends Context {
56
+ export interface Options<Names extends string, Labels extends LabelsInspector = never> extends Context {
41
57
  readonly schedule: Names
42
58
  readonly frames: number
59
+ /** Names the differing entity (`label`): the `labels` inspector a `Session` takes. */
60
+ readonly labels?: Labels
43
61
  }
44
62
 
45
63
  /** A mismatch names the first value; execution errors remain explicit failures. */
@@ -54,6 +72,10 @@ export type CheckResult =
54
72
  readonly first: unknown
55
73
  readonly second: unknown
56
74
  readonly after: string | undefined
75
+ /** The id of the entity the difference is in, when it is in one. */
76
+ readonly entity: number | undefined
77
+ /** That entity's label from `labels`, when it has one. */
78
+ readonly label: string | undefined
57
79
  }
58
80
  | {
59
81
  readonly ok: false
@@ -111,9 +133,17 @@ const difference = (first: Captured, second: Captured, path = "world"): Differen
111
133
  * equals NaN). Maps and sets include iteration order. Functions compare by
112
134
  * identity; weak collections and promises fail explicitly as uninspectable.
113
135
  */
114
- export const check = <S extends Schema.Any, Root, const Names extends string>(
115
- make: (context: Context) => Target<S, Root, Names>,
116
- options: Options<NoInfer<Names>>
136
+ export const check = <
137
+ S extends Schema.Any,
138
+ Root,
139
+ const Names extends string,
140
+ Services extends Record<string, unknown>,
141
+ Resources extends object,
142
+ Machines extends Record<string, unknown>,
143
+ const Labels extends LabelsInspector<Root> = never
144
+ >(
145
+ make: (context: Context) => Target<S, Root, Names, Services, Resources, Machines>,
146
+ options: Options<NoInfer<Names>, Labels> & ValidateLabels<Labels, Services, Resources, Machines>
117
147
  ): CheckResult => {
118
148
  if (!Number.isSafeInteger(options.frames) || options.frames < 0) {
119
149
  return { ok: false, frame: 0, reason: "invalid-options", run: "first", error: "frames must be a finite whole number, 0 or more" }
@@ -138,17 +168,25 @@ export const check = <S extends Schema.Any, Root, const Names extends string>(
138
168
  if (!result.ok) return { ok: false, frame, reason: "failure", run, error: result.error }
139
169
  }
140
170
  run = "first"
141
- const left = capture(first.runtime.debug.dump())
171
+ const leftDump = first.runtime.debug.dump()
172
+ const left = capture(leftDump)
142
173
  if (frame > 0) {
143
174
  run = "second"
144
175
  const result = second.runtime.tryTick(b)
145
176
  if (!result.ok) return { ok: false, frame, reason: "failure", run, error: result.error }
146
177
  }
147
178
  run = "second"
148
- const found = difference(left, capture(second.runtime.debug.dump()))
179
+ const rightDump = second.runtime.debug.dump()
180
+ const found = difference(left, capture(rightDump))
149
181
  if (found !== undefined) {
182
+ const index = /^world\["entities"\]\["(\d+)"\]/.exec(found.path)?.[1]
183
+ const entity = index === undefined ? undefined : (leftDump.entities[Number(index)] ?? rightDump.entities[Number(index)])?.id
184
+ const labels = options.labels as LabelsInspector | undefined
185
+ const label = entity === undefined || labels === undefined
186
+ ? undefined
187
+ : (first.runtime.inspect as (inspector: Inspector.Inspector.Any) => ReadonlyMap<number, string>)(labels).get(entity)
150
188
  const after = frame === 0 ? undefined : locate(make, context, options.schedule, frame)
151
- return { ok: false, frame, reason: "difference", difference: found.path, first: found.first, second: found.second, after }
189
+ return { ok: false, frame, reason: "difference", difference: found.path, first: found.first, second: found.second, after, entity, label }
152
190
  }
153
191
  }
154
192
  return { ok: true, frames: options.frames }
package/src/Format.ts CHANGED
@@ -3,13 +3,15 @@
3
3
  *
4
4
  * The output is meant to be read in a terminal or pasted into a prompt, so it
5
5
  * favors one line per fact and short, stable prefixes (`e12` for entity 12,
6
- * `f40` for frame 40). Numbers are rounded to at most 3 decimals for display;
6
+ * `f40` for frame 40). An entity with a label prints as `player e12`
7
+ * (see {@link entity}). Numbers are rounded to at most 3 decimals for display;
7
8
  * the underlying data keeps exact values.
8
9
  *
9
10
  * @module Format
10
11
  * @docGroup devtools
11
12
  */
12
13
  import type * as Debug from "@typeonce/ritmo/Debug"
14
+ import type { FieldMeta } from "@typeonce/ritmo/Descriptor"
13
15
  import type * as Machine from "@typeonce/ritmo/Machine"
14
16
 
15
17
  /** How much of a nested value the text output prints. */
@@ -20,7 +22,29 @@ export interface ValueOptions {
20
22
  readonly items?: number
21
23
  }
22
24
 
25
+ /**
26
+ * Entity id to label, read when printing entities. A session gets them from
27
+ * its `labels` inspector (a `ReadonlyMap<number, string>` is one); pass
28
+ * `runtime.inspect(Labels)` where a function takes labels as data, such as
29
+ * `Desync.compare`.
30
+ */
31
+ export interface Labels {
32
+ // A method, so a map keyed by branded entity ids (`match.entity.id`) is labels too.
33
+ get(entity: number): string | undefined
34
+ }
35
+
36
+ /**
37
+ * The one way devtools prints an entity: `player e12` when `labels` names
38
+ * it, `e12` otherwise. An empty label counts as none.
39
+ */
40
+ export const entity = (id: number, labels?: Labels): string => {
41
+ const label = labels?.get(id)
42
+ return label === undefined || label === "" ? `e${id}` : `${label} e${id}`
43
+ }
44
+
23
45
  const formatNumber = (value: number): string => {
46
+ // String(-0) is "0": print the sign, so a -0 / 0 difference does not read "0 -> 0"
47
+ if (Object.is(value, -0)) return "-0"
24
48
  if (!Number.isFinite(value) || Number.isInteger(value)) return String(value)
25
49
  const rounded = Math.round(value * 1000) / 1000
26
50
  return String(rounded === 0 ? 0 : rounded)
@@ -139,6 +163,7 @@ export const system = (input: Debug.SystemDescription): string => {
139
163
  add("reads removed", input.removed)
140
164
  if (input.despawned) lines.push(" reads despawned")
141
165
  add("reads relation failures", input.relationFailures)
166
+ add("reads dropped relations", input.droppedRelations)
142
167
  add("services", input.services.filter((name) => !input.consumes.includes(name)))
143
168
  add("consumes (drains each run)", input.consumes)
144
169
  add("may spawn", input.commands.spawns)
@@ -160,17 +185,33 @@ export const lintLines = (lints: ReadonlyArray<Debug.Lint>): Array<string> => [
160
185
  ...(lints.length === 0 ? ["(none)"] : lints.map((lint) => `${lint.severity} ${lint.code}: ${lint.message}`))
161
186
  ]
162
187
 
188
+ /**
189
+ * One field's declared metadata (a constructor's `meta` option, listed by
190
+ * `describe()`) on one line: `hp: points, range [0, 100], "Hit points left."`.
191
+ */
192
+ export const fieldMeta = (field: string, meta: FieldMeta): string => {
193
+ const parts = [
194
+ ...(meta.unit === undefined ? [] : [meta.unit]),
195
+ ...(meta.range === undefined ? [] : [`range [${formatNumber(meta.range[0])}, ${formatNumber(meta.range[1])}]`]),
196
+ ...(meta.hint === undefined ? [] : [JSON.stringify(meta.hint)])
197
+ ]
198
+ return `${field}: ${parts.join(", ")}`
199
+ }
200
+
201
+ const metaLines = (meta: Readonly<Record<string, FieldMeta>>): Array<string> =>
202
+ Object.entries(meta).map(([field, entry]) => ` ${fieldMeta(field, entry)}`)
203
+
163
204
  /** The static description as sections: lints, schema, schedules, systems, access. */
164
205
  export const description = (input: Debug.Description): string => {
165
206
  const lines: Array<string> = []
166
207
  lines.push("# Components")
167
208
  for (const component of input.components) {
168
209
  const notes = [component.storage, ...(component.immutable ? ["immutable"] : []), ...(component.requires.length > 0 ? [`requires ${component.requires.join(", ")}`] : [])]
169
- lines.push(`${component.name} (${notes.join(", ")})`)
210
+ lines.push(`${component.name} (${notes.join(", ")})`, ...metaLines(component.meta))
170
211
  }
171
212
  lines.push("", "# Resources")
172
213
  for (const resource of input.resources) {
173
- lines.push(`${resource.name} (${resource.storage}${resource.present ? "" : ", no value"})`)
214
+ lines.push(`${resource.name} (${resource.storage}${resource.present ? "" : ", no value"})`, ...metaLines(resource.meta))
174
215
  }
175
216
  if (input.events.length > 0) {
176
217
  lines.push("", "# Events")
@@ -205,11 +246,8 @@ export const description = (input: Debug.Description): string => {
205
246
  if (input.schedules.length === 0) lines.push("(none named; call runtime.debug.nameSchedules({...}))")
206
247
  for (const schedule of input.schedules) {
207
248
  lines.push(`${schedule.name}:`)
208
- schedule.steps.forEach((step, index) => {
209
- const text = step.kind === "system" ? step.system
210
- : step.kind === "applyDeferred" ? "<applyDeferred>"
211
- : `<applyStateTransitions${step.schedules.length > 0 ? `: ${step.schedules.join(", ")}` : ""}>`
212
- lines.push(` ${String(index).padStart(2)} ${text}`)
249
+ schedule.steps.forEach((entry, index) => {
250
+ lines.push(` ${String(index).padStart(2)} ${step(entry)}`)
213
251
  })
214
252
  }
215
253
  if (input.systems.length > 0) {
@@ -229,15 +267,21 @@ export const description = (input: Debug.Description): string => {
229
267
  return [...lintLines(input.lints), "", ...lines].join("\n")
230
268
  }
231
269
 
232
- /** One entity per line, then resources, machines, and pending commands. */
233
- export const dump = (input: Debug.WorldDump, options: ValueOptions = {}): string => {
270
+ /** One schedule step: the system's name, or `<applyDeferred>` / `<applyStateTransitions: ...>` for a marker. */
271
+ export const step = (input: Debug.StepDescription): string =>
272
+ input.kind === "system" ? input.system
273
+ : input.kind === "applyDeferred" ? "<applyDeferred>"
274
+ : `<applyStateTransitions${input.schedules.length > 0 ? `: ${input.schedules.join(", ")}` : ""}>`
275
+
276
+ /** One entity per line (named with `labels`), then resources, machines, and pending commands. */
277
+ export const dump = (input: Debug.WorldDump, options: ValueOptions = {}, labels?: Labels): string => {
234
278
  const lines: Array<string> = [
235
279
  `frame ${input.frame} (tick ${input.tick}), ${input.entities.length} of ${input.entityCount} entities`
236
280
  ]
237
- for (const entity of input.entities) {
238
- const components = Object.entries(entity.components).map(([name, component]) => `${name}=${value(component, options)}`)
239
- const relations = Object.entries(entity.relations).map(([name, target]) => `${name}->e${target}`)
240
- lines.push(`e${entity.id} ${[...components, ...relations].join(" ")}`)
281
+ for (const dumped of input.entities) {
282
+ const components = Object.entries(dumped.components).map(([name, component]) => `${name}=${value(component, options)}`)
283
+ const relations = Object.entries(dumped.relations).map(([name, target]) => `${name}->${entity(target, labels)}`)
284
+ lines.push(`${entity(dumped.id, labels)} ${[...components, ...relations].join(" ")}`)
241
285
  }
242
286
  const resources = Object.entries(input.resources)
243
287
  if (resources.length > 0) {
@@ -274,28 +318,33 @@ export const streams = (input: ReadonlyArray<Debug.StreamStatus>): string => {
274
318
  return lines.join("\n")
275
319
  }
276
320
 
277
- const effect = (input: Debug.Effect, options: ValueOptions): string => {
321
+ const effect = (input: Debug.Effect, options: ValueOptions, labels: Labels | undefined): string => {
322
+ const id = entity(input.entity, labels)
278
323
  switch (input.kind) {
279
324
  case "spawn":
280
- return `spawn e${input.entity} ${Object.entries(input.components).map(([name, component]) => `${name}=${value(component, options)}`).join(" ")}`
325
+ return `spawn ${id} ${Object.entries(input.components).map(([name, component]) => `${name}=${value(component, options)}`).join(" ")}`
281
326
  case "despawn":
282
- return `despawn e${input.entity}`
327
+ return `despawn ${id}`
283
328
  case "insert":
284
- return `insert e${input.entity} ${input.component}=${value(input.value, options)}`
329
+ return `insert ${id} ${input.component}=${value(input.value, options)}`
285
330
  case "overwrite":
286
- return `insert e${input.entity} ${input.component} ${change(input.before, input.after, options)}`
331
+ return `insert ${id} ${input.component} ${change(input.before, input.after, options)}`
287
332
  case "remove":
288
- return `remove e${input.entity} ${input.component}`
333
+ return `remove ${id} ${input.component}`
289
334
  case "relate":
290
- return `relate e${input.entity} ${input.relation}->e${input.target}`
335
+ return `relate ${id} ${input.relation}->${entity(input.target, labels)}`
291
336
  case "unrelate":
292
- return `unrelate e${input.entity} ${input.relation}`
337
+ return `unrelate ${id} ${input.relation}`
293
338
  case "relationFailure":
294
- return `relation failure e${input.entity} ${input.relation}: ${input.error}`
339
+ return `relation failure ${id} ${input.relation}: ${input.error}`
340
+ case "relationDropped": {
341
+ const target = entity(input.target, labels)
342
+ return `${input.relation} from ${id} to ${target} dropped: ${target} despawned`
343
+ }
295
344
  case "requirementViolated":
296
- return `skipped ${input.command} e${input.entity}: ${input.component} requires ${input.missing}`
345
+ return `skipped ${input.command} ${id}: ${input.component} requires ${input.missing}`
297
346
  case "staleTarget":
298
- return `skipped ${input.command} e${input.entity}: id spawned in an earlier run`
347
+ return `skipped ${input.command} ${id}: id spawned in an earlier run`
299
348
  }
300
349
  }
301
350
 
@@ -314,6 +363,8 @@ export type LineKind =
314
363
  | "transition"
315
364
  | "restore"
316
365
  | "ignored"
366
+ /** A read the writing system declared, under a `why` line; only `why` and `whyResource` with `depth` above 1 print them. */
367
+ | "read"
317
368
 
318
369
  /**
319
370
  * The text for a failed tick result nobody read: who failed, with what, how
@@ -392,6 +443,8 @@ export interface Line {
392
443
  readonly system: string | undefined
393
444
  /** The entity the line is about, when there is one. */
394
445
  readonly entity: number | undefined
446
+ /** That entity's label, when the labels given to {@link lines} name it. */
447
+ readonly label: string | undefined
395
448
  /** The component, resource, event, machine, or stream the line is about. */
396
449
  readonly subject: string | undefined
397
450
  readonly text: string
@@ -400,13 +453,27 @@ export interface Line {
400
453
  * the current state, or a skip that discarded nothing.
401
454
  */
402
455
  readonly noop: boolean
456
+ /**
457
+ * How far back the line is from the value asked about: 0 for every
458
+ * journal line and each change `why` lists; 1 for a read the system
459
+ * behind a depth-0 line declared, 2 for one behind that, and so on
460
+ * (`why(..., { depth })`). Lines above 0 are `read` lines and print
461
+ * indented under the line they explain.
462
+ */
463
+ readonly depth: number
403
464
  }
404
465
 
405
466
  /**
406
- * Splits one trace event into printable lines. Frame and schedule
407
- * boundaries produce no lines.
467
+ * Splits one trace event into printable lines, naming entities with
468
+ * `labels`. Frame and schedule boundaries produce no lines.
408
469
  */
409
- export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): ReadonlyArray<Line> => {
470
+ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}, labels?: Labels): ReadonlyArray<Line> =>
471
+ rawLines(event, options, labels).map((line) => {
472
+ const label = line.entity === undefined ? undefined : labels?.get(line.entity)
473
+ return { ...line, label: label === "" ? undefined : label, depth: 0 }
474
+ })
475
+
476
+ const rawLines = (event: Debug.TraceEvent, options: ValueOptions, labels: Labels | undefined): ReadonlyArray<Omit<Line, "label" | "depth">> => {
410
477
  switch (event.type) {
411
478
  case "frame":
412
479
  case "schedule.start":
@@ -454,7 +521,7 @@ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): Read
454
521
  text: `sent ${event.event} ${value(event.value)} (runtime.send)`
455
522
  }]
456
523
  case "deferred": {
457
- const result: Array<Line> = []
524
+ const result: Array<Omit<Line, "label" | "depth">> = []
458
525
  for (const command of event.commands) {
459
526
  if (command.effects.length === 0) {
460
527
  result.push({ kind: "effect", frame: event.frame, schedule: event.schedule, system: command.system, entity: undefined, subject: undefined, noop: true, text: `${event.marker}: ${command.tag} had no effect` })
@@ -468,7 +535,7 @@ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): Read
468
535
  entity: applied.entity,
469
536
  subject: "component" in applied ? applied.component : "relation" in applied ? applied.relation : undefined,
470
537
  noop: applied.kind === "overwrite" && sameValue(applied.before, applied.after),
471
- text: `${event.marker}: ${effect(applied, options)}`
538
+ text: `${event.marker}: ${effect(applied, options, labels)}`
472
539
  })
473
540
  }
474
541
  }
@@ -476,13 +543,13 @@ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): Read
476
543
  }
477
544
  case "system": {
478
545
  const base = { frame: event.frame, schedule: event.schedule, system: event.system }
479
- const result: Array<Line> = []
546
+ const result: Array<Omit<Line, "label" | "depth">> = []
480
547
  const rolledBack = event.outcome === "ok" ? "" : " (rolled back)"
481
548
  if (event.outcome !== "ok") {
482
549
  result.push({ ...base, kind: "failure", entity: undefined, subject: undefined, noop: false, text: `${event.outcome}: ${value(event.error, options)}` })
483
550
  }
484
551
  for (const write of event.writes) {
485
- result.push({ ...base, kind: "write", entity: write.entity, subject: write.component, noop: sameValue(write.before, write.after), text: `write e${write.entity} ${write.component} ${change(write.before, write.after, options)}${rolledBack}` })
552
+ result.push({ ...base, kind: "write", entity: write.entity, subject: write.component, noop: sameValue(write.before, write.after), text: `write ${entity(write.entity, labels)} ${write.component} ${change(write.before, write.after, options)}${rolledBack}` })
486
553
  }
487
554
  for (const write of event.resources) {
488
555
  result.push({ ...base, kind: "resource", entity: undefined, subject: write.resource, noop: sameValue(write.before, write.after), text: `resource ${write.resource} ${change(write.before, write.after, options)}${rolledBack}` })
@@ -510,6 +577,6 @@ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): Read
510
577
  }
511
578
  }
512
579
 
513
- /** `f12 update Game/Move write e3 ...` */
580
+ /** `f12 update Game/Move write e3 ...`; a line with `depth` above 0 prints its text alone, indented two spaces per level. */
514
581
  export const line = (input: Line): string =>
515
- `f${input.frame} ${input.schedule} ${input.system ?? "-"} ${input.text}${input.noop && (input.kind === "write" || input.kind === "resource" || input.kind === "effect") ? " (unchanged)" : ""}`
582
+ input.depth > 0 ? `${" ".repeat(input.depth)}${input.text}` : `f${input.frame} ${input.schedule} ${input.system ?? "-"} ${input.text}${input.noop && (input.kind === "write" || input.kind === "resource" || input.kind === "effect") ? " (unchanged)" : ""}`