@typeonce/ritmo-devtools 0.12.0 → 0.14.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.
package/src/Format.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  * @docGroup devtools
11
11
  */
12
12
  import type * as Debug from "@typeonce/ritmo/Debug"
13
+ import type * as Machine from "@typeonce/ritmo/Machine"
13
14
 
14
15
  /** How much of a nested value the text output prints. */
15
16
  export interface ValueOptions {
@@ -87,6 +88,15 @@ export const value = (input: unknown, options: ValueOptions = {}): string => {
87
88
  return go(input, 0)
88
89
  }
89
90
 
91
+ /**
92
+ * One machine value: its state's name, then its fields when it has any
93
+ * (`Talking {speaker:"Mira",page:2}`).
94
+ */
95
+ export const state = (input: Machine.AnyValue, options: ValueOptions = {}): string => {
96
+ const { _tag, ...fields } = input
97
+ return Object.keys(fields).length === 0 ? _tag : `${_tag} ${value(fields, options)}`
98
+ }
99
+
90
100
  const list = (items: ReadonlyArray<string>): string => items.length === 0 ? "-" : items.join(", ")
91
101
 
92
102
  /** One transition as `Machine from -> to`; a sub-state without a value prints `(inactive)`. */
@@ -122,6 +132,7 @@ export const system = (input: Debug.SystemDescription): string => {
122
132
  add("reads events", input.events.reads)
123
133
  add("emits events", input.events.writes)
124
134
  add("reads machines", input.machines.reads)
135
+ add("updates machine fields", input.machines.updates)
125
136
  add("queues next state", input.machines.next)
126
137
  add("reads transitions", input.machines.transitions)
127
138
  add("reads transition events", input.machines.transitionEvents)
@@ -176,7 +187,7 @@ export const description = (input: Debug.Description): string => {
176
187
  if (input.machines.length > 0) {
177
188
  lines.push("", "# Machines")
178
189
  for (const machine of input.machines) {
179
- const current = !machine.provided ? "(not provided)" : machine.current === undefined ? "(inactive)" : String(machine.current)
190
+ const current = !machine.provided ? "(not provided)" : machine.current === undefined ? "(inactive)" : state(machine.current)
180
191
  lines.push(`${machine.name} = ${current} [${machine.states.join(" | ")}]${machine.within === undefined ? "" : ` within ${machine.within}`}`)
181
192
  }
182
193
  }
@@ -238,10 +249,10 @@ export const dump = (input: Debug.WorldDump, options: ValueOptions = {}): string
238
249
  lines.push("machines:")
239
250
  for (const [name, machine] of machines) {
240
251
  const extra = [
241
- machine.pending === undefined ? undefined : `pending ${String(machine.pending)}`,
242
- machine.previous === undefined ? undefined : `previous ${String(machine.previous)}`
252
+ machine.pending === undefined ? undefined : `pending ${state(machine.pending)}`,
253
+ machine.previous === undefined ? undefined : `previous ${state(machine.previous)}`
243
254
  ].filter((part) => part !== undefined)
244
- lines.push(` ${name}=${String(machine.current)}${extra.length > 0 ? ` (${extra.join(", ")})` : ""}`)
255
+ lines.push(` ${name}=${state(machine.current)}${extra.length > 0 ? ` (${extra.join(", ")})` : ""}`)
245
256
  }
246
257
  }
247
258
  if (input.pendingCommands.length > 0) {
@@ -293,6 +304,7 @@ export type LineKind =
293
304
  | "write"
294
305
  | "resource"
295
306
  | "event"
307
+ | "machine"
296
308
  | "nextState"
297
309
  | "command"
298
310
  | "effect"
@@ -478,8 +490,11 @@ export const lines = (event: Debug.TraceEvent, options: ValueOptions = {}): Read
478
490
  for (const emitted of event.events) {
479
491
  result.push({ ...base, kind: "event", entity: undefined, subject: emitted.event, noop: false, text: `emit ${emitted.event} ${value(emitted.values, options)}${rolledBack}` })
480
492
  }
493
+ for (const write of event.machines) {
494
+ result.push({ ...base, kind: "machine", entity: undefined, subject: write.machine, noop: sameValue(write.before, write.after), text: `machine ${write.machine} ${change(write.before, write.after, options)}${rolledBack}` })
495
+ }
481
496
  for (const next of event.nextStates) {
482
- result.push({ ...base, kind: "nextState", entity: undefined, subject: next.machine, noop: false, text: `next state ${next.machine}=${next.value === undefined ? "(cleared)" : String(next.value)}${rolledBack}` })
497
+ result.push({ ...base, kind: "nextState", entity: undefined, subject: next.machine, noop: false, text: `next state ${next.machine}=${next.value === undefined ? "(cleared)" : state(next.value, options)}${rolledBack}` })
483
498
  }
484
499
  if (event.commands.length > 0) {
485
500
  const counts = new Map<string, number>()
package/src/Lint.ts CHANGED
@@ -6,13 +6,16 @@
6
6
  * Run it from a game's `check` script with the CLI:
7
7
  *
8
8
  * ```sh
9
- * ritmo-devtools lint src/simulation.ts
9
+ * ritmo-devtools lint src/lint.ts
10
10
  * ```
11
11
  *
12
12
  * The entry module exports `lintTarget`, a function that builds the game's
13
13
  * headless runtime (made with `debug: { hostClock }`) and names its schedules: the
14
14
  * ones ticked headless in `schedules`, and the ones that need a renderer or
15
15
  * other host services in `describe` (described and linted, never run).
16
+ * Keep the entry beside the simulation, not inside it, and import the host
17
+ * schedules inside `lintTarget`: the entry is then the one module that loads
18
+ * both, and the simulation never imports render or audio code.
16
19
  *
17
20
  * Use `Session.make(...).describe()` instead to read the lints while
18
21
  * debugging; this module is for the pass/fail check.
@@ -22,8 +25,11 @@
22
25
  *
23
26
  * @example
24
27
  * ```ts
25
- * // src/simulation.ts
26
- * export const lintTarget = (): Lint.Target<typeof Game.schema, typeof Game.schema> => {
28
+ * // src/lint.ts
29
+ * import { createSimulation } from "./simulation.ts"
30
+ *
31
+ * export const lintTarget = async (): Promise<Lint.Target<typeof Game.schema, typeof Game.schema>> => {
32
+ * const { render } = await import("./render.ts")
27
33
  * const sim = createSimulation({ keyboard: Keyboard.scripted(bindings, []) })
28
34
  * return { runtime: sim.runtime, schedules: { setup: sim.setup, update: sim.update }, describe: { render } }
29
35
  * }
package/src/Monitor.ts CHANGED
@@ -175,7 +175,7 @@ const accessOf = (system: Debug.SystemDescription): Access => {
175
175
  eventReads: system.events.reads,
176
176
  eventWrites: system.events.writes,
177
177
  machineReads: system.machines.reads.filter((name) => !system.machines.next.includes(name)),
178
- machineWrites: system.machines.next
178
+ machineWrites: [...system.machines.next, ...system.machines.updates]
179
179
  }
180
180
  }
181
181
 
@@ -371,8 +371,8 @@ export const attach = <S extends Schema.Any, Root>(runtime: Target<S, Root>, opt
371
371
  if (machines.length > 0) {
372
372
  parts.push("<h3>State machines</h3>")
373
373
  for (const [name, machine] of machines) {
374
- const pending = machine.pending === undefined ? "" : ` <span class="btm-dim">→ ${escape(String(machine.pending))} (queued)</span>`
375
- parts.push(`<div class="btm-row"><span>${escape(short(name))}</span><span class="btm-num">${escape(String(machine.current))}${pending}</span><span></span></div>`)
374
+ const pending = machine.pending === undefined ? "" : ` <span class="btm-dim">→ ${escape(Format.state(machine.pending))} (queued)</span>`
375
+ parts.push(`<div class="btm-row"><span>${escape(short(name))}</span><span class="btm-num">${escape(Format.state(machine.current))}${pending}</span><span></span></div>`)
376
376
  }
377
377
  }
378
378
 
package/src/Replay.ts CHANGED
@@ -50,7 +50,7 @@ import type * as Debug from "@typeonce/ritmo/Debug"
50
50
  import type { Descriptor } from "@typeonce/ritmo/Descriptor"
51
51
  import type * as Requirement from "@typeonce/ritmo/Requirement"
52
52
  import * as Result from "@typeonce/ritmo/Result"
53
- import type { AnyScheduleOrder, ExecutableScheduleDefinition } from "@typeonce/ritmo/Schedule"
53
+ import type { AnyScheduleOrder, ExecutableScheduleDefinition, IsPlain, Source } from "@typeonce/ritmo/Schedule"
54
54
  import type { Schema } from "@typeonce/ritmo/Schema"
55
55
  import type * as Snapshot from "@typeonce/ritmo/Snapshot"
56
56
 
@@ -65,29 +65,6 @@ type AnySchedule<S extends Schema.Any, Root> = ExecutableScheduleDefinition<S, a
65
65
  /** The `@typeonce/ritmo-devtools` version written into replay files. */
66
66
  export const version = libraryVersion
67
67
 
68
- /** An input service: one value per call, such as a keyboard's actions this step. */
69
- export interface Source<Data> {
70
- readonly snapshot: () => Data
71
- }
72
-
73
- /**
74
- * Whether a type is plain data (what JSON keeps): no functions, maps, sets,
75
- * or class instances with methods. Recursive types are checked once.
76
- */
77
- export type IsPlain<T> = false extends PlainMember<T, never> ? false : true
78
-
79
- // Checks one member of a union at a time (the conditional distributes), so a
80
- // recursive type is recognised when it comes back (`Seen`).
81
- type PlainMember<T, Seen> =
82
- T extends string | number | boolean | null | undefined ? true
83
- : [T] extends [Seen] ? true
84
- : T extends (...args: ReadonlyArray<never>) => unknown ? false
85
- : T extends ReadonlyArray<infer Element> ? PlainMember<Element, Seen | T>
86
- : T extends object ? PlainField<T, keyof T, Seen | T>
87
- : false
88
-
89
- type PlainField<T, K extends keyof T, Seen> = K extends keyof T ? PlainMember<T[K], Seen> : never
90
-
91
68
  type ServiceNeeds<Schedule> = Extract<Requirement.Of<Schedule>, Descriptor<"service", string, any>>
92
69
 
93
70
  type UnrecordableService<Need> =
@@ -160,7 +137,8 @@ export const memorySink = (): Sink & { readonly files: ReadonlyArray<ReplayFile>
160
137
  /** What a recorder needs from a runtime: made with `debug: { hostClock }`, with snapshots available. */
161
138
  export interface Recordable<S extends Schema.Any, Root> {
162
139
  readonly debug: Debug.Handle<S, Root>
163
- readonly snapshot: () => Snapshot.WorldSnapshot
140
+ readonly snapshot: () => Result.Result<Snapshot.WorldSnapshot, Snapshot.SnapshotError>
141
+ readonly checksum: () => Result.Result<string, Snapshot.SnapshotError>
164
142
  readonly services: Readonly<Record<string, unknown>>
165
143
  readonly inspect: (inspector: never) => unknown
166
144
  }
@@ -202,7 +180,7 @@ export interface Recorder {
202
180
  readonly stop: () => void
203
181
  }
204
182
 
205
- /** FNV-1a over a string, as 8 hex digits: a cheap fingerprint for checkpoints and schemas. */
183
+ /** FNV-1a over a string, as 8 hex digits: a cheap fingerprint for schemas and encode failures. */
206
184
  const fingerprint = (text: string): string => {
207
185
  let hash = 0x811c9dc5
208
186
  for (let index = 0; index < text.length; index++) {
@@ -224,7 +202,10 @@ export const schemaHash = <S extends Schema.Any, Root>(debug: Debug.Handle<S, Ro
224
202
  }))
225
203
  }
226
204
 
227
- const worldHash = (snapshot: Snapshot.WorldSnapshot): string => fingerprint(JSON.stringify(snapshot))
205
+ // The world's `runtime.checksum()`. A world that cannot be saved hashes its
206
+ // encode failure, so a replay that reaches it diverges visibly.
207
+ const worldHash = (checksum: Result.Result<string, Snapshot.SnapshotError>): string =>
208
+ checksum.ok ? checksum.value : fingerprint(JSON.stringify(checksum.error))
228
209
 
229
210
  const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null
230
211
 
@@ -279,8 +260,10 @@ export const recorder = <S extends Schema.Any, Root, const Recorded extends AnyS
279
260
 
280
261
  const takePoint = () => {
281
262
  const snapshot = runtime.snapshot()
282
- points.push({ tick, snapshot, pendingCommands: runtime.debug.dump({ limit: 0 }).pendingCommands.length })
283
- checkpoints.push({ tick, hash: worldHash(snapshot) })
263
+ // A tick whose world an `encode` rejects is no starting point; the window keeps the previous one.
264
+ if (!snapshot.ok) return
265
+ points.push({ tick, snapshot: snapshot.value, pendingCommands: runtime.debug.dump({ limit: 0 }).pendingCommands.length })
266
+ checkpoints.push({ tick, hash: worldHash(runtime.checksum()) })
284
267
  const windowStart = tick - keepTicks
285
268
  let firstNeeded = -1
286
269
  for (let index = 0; index < points.length; index++) if (points[index]!.tick <= windowStart) firstNeeded = index
@@ -303,7 +286,8 @@ export const recorder = <S extends Schema.Any, Root, const Recorded extends AnyS
303
286
  takePoint()
304
287
 
305
288
  const save = (reason: string): ReplayFile => {
306
- const start = points[0]!
289
+ const start = points[0]
290
+ if (start === undefined) throw new Error("no tick of this run could be saved: an `encode` rejected the world every time (see runtime.snapshot())")
307
291
  const file: ReplayFile = {
308
292
  format: "ritmo-replay",
309
293
  version: 1,
@@ -389,6 +373,8 @@ export type ReplayError =
389
373
  | { readonly _tag: "SchemaMismatch"; readonly message: "replay recorded with an older schema"; readonly recorded: string; readonly current: string }
390
374
  | { readonly _tag: "MissingSchedule"; readonly schedule: string }
391
375
  | { readonly _tag: "RestoreFailed"; readonly error: Snapshot.RestoreError }
376
+ /** The world at the start of an extract could not be saved. */
377
+ | { readonly _tag: "SnapshotFailed"; readonly error: Snapshot.SnapshotError }
392
378
 
393
379
  /** Checks the shape of untrusted replay data (`JSON.parse` output). */
394
380
  export const parse = (data: unknown): Result.Result<ReplayFile, ReplayError> => {
@@ -427,7 +413,8 @@ export interface Playback {
427
413
  export interface Target<S extends Schema.Any, Root> {
428
414
  readonly hostClock: HostClock.HostClock
429
415
  readonly runtime: Session.Target<S, Root> & {
430
- readonly snapshot: () => Snapshot.WorldSnapshot
416
+ readonly snapshot: () => Result.Result<Snapshot.WorldSnapshot, Snapshot.SnapshotError>
417
+ readonly checksum: () => Result.Result<string, Snapshot.SnapshotError>
431
418
  readonly restore: (data: unknown) => Result.Result<void, Snapshot.RestoreError>
432
419
  readonly send: (descriptor: never, value: never) => void
433
420
  }
@@ -451,8 +438,8 @@ export interface ReplaySession<S extends Schema.Any, Names extends string> {
451
438
  readonly play: (options?: { readonly to?: number }) => Rendered.Rendered<PlayResult>
452
439
  /** Hashes of the world at the end of each replayed tick so far. */
453
440
  readonly hashes: () => ReadonlyMap<number, string>
454
- /** The world as plain data now. */
455
- readonly snapshot: () => Snapshot.WorldSnapshot
441
+ /** The world as plain data now, or the value an `encode` rejected. */
442
+ readonly snapshot: () => Result.Result<Snapshot.WorldSnapshot, Snapshot.SnapshotError>
456
443
  }
457
444
 
458
445
  /**
@@ -492,7 +479,7 @@ export const session = <S extends Schema.Any, Root>(
492
479
  const replay = Session.make(target.runtime, { schedules: { [file.schedule]: schedule }, hostClock: target.hostClock })
493
480
  const send = target.runtime.send as (descriptor: { readonly kind: "event"; readonly name: string; readonly key: symbol }, value: unknown) => void
494
481
  const events = new Map(target.runtime.debug.describe().events.map(({ name }) => [name, { kind: "event" as const, name, key: Symbol.for(`ritmo/event/${name}`) }]))
495
- const hashes = new Map<number, string>([[ran, worldHash(target.runtime.snapshot())]])
482
+ const hashes = new Map<number, string>([[ran, worldHash(target.runtime.checksum())]])
496
483
  const recorded = new Map(file.checkpoints.map(({ tick, hash }) => [tick, hash] as const))
497
484
  const last = file.ticks.at(-1)?.tick ?? file.start.tick
498
485
 
@@ -505,7 +492,7 @@ export const session = <S extends Schema.Any, Root>(
505
492
  // `until` runs after each frame: the tick is checked, and the next one's input set up before it runs.
506
493
  until: () => {
507
494
  ran += 1
508
- const hash = worldHash(target.runtime.snapshot())
495
+ const hash = worldHash(target.runtime.checksum())
509
496
  hashes.set(ran, hash)
510
497
  const expected = recorded.get(ran)
511
498
  if (expected !== undefined && expected !== hash) diverged.push({ tick: ran, recorded: expected, replayed: hash })
@@ -579,6 +566,7 @@ export const extract = <S extends Schema.Any, Root>(
579
566
  if (!opened.ok) return opened
580
567
  opened.value.play({ to: range.from - 1 })
581
568
  const start = opened.value.snapshot()
569
+ if (!start.ok) return Result.failure({ _tag: "SnapshotFailed", error: start.error })
582
570
  // Each kept tick carries its sources' values in full, so the extract does not depend on earlier ticks.
583
571
  const latest = new Map<string, ReadonlyArray<unknown>>()
584
572
  const ticks: Array<TickRecord> = []
@@ -592,7 +580,7 @@ export const extract = <S extends Schema.Any, Root>(
592
580
  return Result.success({
593
581
  ...file,
594
582
  reason: `${file.reason} (ticks ${range.from}-${range.to})`,
595
- start: { tick: range.from - 1, snapshot: start, pendingCommands: 0 },
583
+ start: { tick: range.from - 1, snapshot: start.value, pendingCommands: 0 },
596
584
  ticks,
597
585
  checkpoints
598
586
  })
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /** Debug sessions, trace history, text reports, and a live browser monitor for ritmo runtimes. */
2
2
  export * as Format from "./Format.ts"
3
+ export * as Desync from "./Desync.ts"
3
4
  export * as Determinism from "./Determinism.ts"
4
5
  export * as Invariant from "./Invariant.ts"
5
6
  export * as Lint from "./Lint.ts"
@@ -3,4 +3,4 @@
3
3
  * `package.json` by `scripts/sync-version.ts` (run by \`pnpm version-packages\`)
4
4
  * and checked by a test.
5
5
  */
6
- export const libraryVersion = "0.12.0"
6
+ export const libraryVersion = "0.14.0"