All files / player-engine/src/core/characterization harness.ts

95.47% Statements 232/243
90.25% Branches 139/154
94.38% Functions 84/89
96.15% Lines 200/208

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613                                                                                                667x 667x             178x                                                                                                                                                                                               322x 966x   2162x     1368x     322x   4186x                                         917x 917x 2123941x 51x 4322x 917x           2x 2x 1868x           2x       288749x   36x 501432x   36x 6797x                 904x 904x 1837024x 1835234x 1837024x 1837024x   10020x 904x       899x 899x   866x 904x   11x 11x     11x 11x 11x         918512x         5816x       19x     204x 962x 311x 17x           4052x 4156x 23767x                             4270x 4055x 4052x 4270x 1632x         2472x 1607x               917x                       919x 919x 919x 919x 919x 919x 919x 919x 919x 919x 278729x 919x 7368x     919x 919x   919x           10020x     2153x     3664x 3664x   919x 17x 5x   919x     722x     919x     919x 4314x   4270x 6010x       3376x 919x 919x 919x               912x 912x   912x 912x 912x                       8x 8x 7x 7x                 912x 912x 912x 6524x 6524x       6524x   912x 912x 20139x 204x 204x 204x           204x 204x   19935x 19935x 21842x       19935x 19935x   912x 912x 912x 912x 234438x 234438x 234438x 204x   204x 204x 204x 204x               234438x     234438x 703314x 1624564x 6392x 6392x         234438x 234438x 234438x 234438x 234438x 322x 322x         919x 919x   919x 919x   4x         4314x   919x   919x                               13686x 12767x         36x                             55x 55x 171x 171x 153x 153x   171x 1026x 1026x 954x 954x 954x   171x   55x       1933x 1933x 2844x 2790x   1879x       374x 374x 374x       62630x 22748x   39882x 36834x 42789x         30049x 30049x 30049x 3016x 3016x 15518x   14476x 14476x 1765x               722x 722x 722x 2888x 2888x 4x   722x    
import type { BeMusicEvent, BeMusicJSON } from '@be-music/chart-source';
import { autoPlay, manualPlay } from '../play.ts';
import {
  PlayerInterruptedError,
  type AudioSession,
  type CreatePlayerInputRuntimeContext,
  type CreatePlayerUIRuntimeContext,
  type PlayerOptions,
  type PlayerSummary,
} from '../engine-types.ts';
import type { PlayerInputCommand } from '../input-signal-bus.ts';
import type { PlayerUICommand, PlayerUIFrameNote, PlayerUIFramePayload } from '../ui-signal-bus.ts';
import type { BeMusicReplay, ReplayRulesetResult } from '../../replay/format.ts';
import { findReplayNotSimulatedReason, type ReplayNotSimulatedReason } from '../../replay/rejudge.ts';
import { REPLAY_SIMULATOR_RULESETS, simulateReplay } from '../../replay/simulate.ts';
import { createVirtualClock } from './virtual-clock.ts';
 
/**
 * Test support: runs one `manualPlay` / `autoPlay` with scripted input, a test audio session and a recording UI
 * runtime, and collects everything a host could observe of it — the summary, the replay and its re-simulations, the
 * audio session's calls, the judge cues, the UI commands and frames, the host callbacks and the text output — as plain
 * data for the characterization snapshots. Times are milliseconds of the clock the play ran on, from the call that
 * started it (play-clock milliseconds when the lead-in is 0).
 */
 
export type CharacterizationDriver = 'manual' | 'auto';
 
/** One scripted input, `atMs` after the play started. Lanes are chart channels (`'11'`, `'16'`, ...). */
export type ScriptStep =
  /**
   * Keys go down, as the web input runtime sends them: a `lane-input` and a `kitty-state` press. `pressedAtMs` stamps
   * both with the wall-clock time the key really went down, as the web runtime stamps an event's `timeStamp`.
   */
  | { atMs: number; down: readonly string[]; pressedAtMs?: number }
  /** Keys come up: a `kitty-state` release, stamped with `pressedAtMs` (the instant they came up) when given. */
  | { atMs: number; up: readonly string[]; pressedAtMs?: number }
  /**
   * A `lane-input` alone, as a terminal without key release events sends it. `pressedAtMs` stamps the command with the
   * wall-clock time the key really went down (the engine judges it there, within 50 ms).
   */
  | { atMs: number; press: readonly string[]; pressedAtMs?: number }
  /** Any other input command (interrupt, pause, tempo, view, high speed, seek). */
  | { atMs: number; command: PlayerInputCommand }
  /** Several commands pushed at once, so the engine drains them together (seeks coalesce within a drain). */
  | { atMs: number; commands: readonly PlayerInputCommand[] };
 
/** A key going down at `atMs` and up `holdMs` later. */
export function tap(atMs: number, lanes: string | readonly string[], holdMs = 60): ScriptStep[] {
  const list = typeof lanes === 'string' ? [lanes] : lanes;
  return [
    { atMs, down: list },
    { atMs: atMs + holdMs, up: list },
  ];
}
 
export function command(atMs: number, input: PlayerInputCommand): ScriptStep {
  return { atMs, command: input };
}
 
export interface TestAudioSessionOptions {
  /** `chartStartDelayMs` the session reports. */
  chartStartDelayMs?: number;
  /** How far the session's write head (`scheduledSeconds`) runs ahead of what is audible. */
  writeAheadMs?: number;
  /** Whether the session reports a clock (`getClockState`); without one the engine runs on the scheduler's clock. */
  clock?: boolean;
  /**
   * The audible clock moves in steps of this many ms, as Web Audio's `currentTime` moves a render quantum at a time,
   * while the wall clock (`pressedAt`) moves smoothly. Without it the audible clock moves smoothly too.
   */
  quantumMs?: number;
  /** Whether the session places the realtime sounds at their due time (`scheduleEventAt`), as the web session does. */
  schedulesAhead?: boolean;
}
 
export interface CharacterizationPlay {
  driver: CharacterizationDriver;
  chart: BeMusicJSON;
  /** Engine options over the harness's own (no lead-in, the test runtimes and callbacks, replay recording). */
  options?: PlayerOptions;
  script?: readonly ScriptStep[];
  /**
   * Whether the scripted input runtime declares its key releases (`PlayerInputRuntime.reportsKeyReleases`). By default
   * it does, as the web input runtime does, unless the script sends terminal presses (`press` steps): the engine then
   * detects them.
   */
  reportsKeyReleases?: boolean;
  /** The test audio session (default), or none at all (`audio: false`). */
  audio?: false | TestAudioSessionOptions;
  /** With a UI runtime (default), or without one: the engine then writes its no-TUI trace to the output. */
  ui?: boolean;
  /** Hold the play open after its chart (`holdAfterChart`) and end it this long after `onSettled`. */
  holdAfterChart?: { releaseAfterMs: number };
  /**
   * Chart seconds to take a {@link snapshotJudgeState} at: on the first frame at or past each, of the last seek
   * generation (a seek takes them again from its own frame on).
   */
  captureAt?: readonly number[];
  /** Observe a frame synchronously without retaining its mutable notes or summary. */
  onFrame?: (frame: Readonly<PlayerUIFramePayload>) => void;
}
 
/** What a host could observe of one play. */
export interface PlayObservation {
  /** `completed`, `interrupted: <reason>` (a thrown `PlayerInterruptedError`) or `error: <message>`. */
  outcome: string;
  /** When the call settled. */
  endedAtMs: number;
  summary?: PlayerSummary;
  replay?: BeMusicReplay;
  /** `simulateReplay` of the recorded log under each ruleset that can read it. */
  simulated?: Record<string, ReplayRulesetResult>;
  /** Why a ruleset cannot read the recorded log (a bare gauge it lacks), as re-judging reports it. */
  notSimulated?: Record<string, ReplayNotSimulatedReason>;
  /** The audio session's calls. */
  audio: string[];
  /** Judgment cues (`publishJudgeCombo`), with the gauge as it stood then. */
  judges: string[];
  /** UI commands (lane flashes, long notes, POOR BGA). */
  ui: string[];
  /**
   * Frames published, the last one, and when each note, mine and invisible note first showed as judged (again, after a
   * seek); `generations` lists the first frame of each seek generation with its clock.
   */
  frames: { count: number; last?: string; judged: string[]; generations?: string[] };
  /** Host callbacks and runtime lifecycle. */
  host: string[];
  /** `onLog` entries. */
  log: string[];
  /** Text written to `writeOutput`. */
  output: string[];
  /** The judge state at each of {@link CharacterizationPlay.captureAt}, by its chart second. */
  captured?: Record<string, JudgeStateSnapshot>;
}
 
/**
 * The judge state a host can read off a frame: the judgment counts, the scores, the combos and the gauge, and which
 * notes, mines and invisible notes show as judged (a long note with the beat it stays visible until).
 */
export interface JudgeStateSnapshot {
  counts: Record<string, number>;
  gauge: number | undefined;
  notes: string[];
  landmines: string[];
  invisibleNotes: string[];
}
 
/**
 * Snapshots the judge state `frame` shows. Two plays whose snapshots at a chart second are equal show the same play
 * there.
 */
export function snapshotJudgeState(frame: Readonly<PlayerUIFramePayload>): JudgeStateSnapshot {
  const { gauge, course, ...counts } = frame.summary;
  const judged = (notes: readonly PlayerUIFrameNote[] | undefined): string[] =>
    (notes ?? [])
      .filter((note) => note.judged)
      .map(
        (note) =>
          `${note.channel}@${formatNumber(note.seconds)}` +
          `${note.visibleUntilBeat === undefined ? '' : ` until=${formatNumber(note.visibleUntilBeat)}`}`,
      );
  return {
    counts: Object.fromEntries(
      Object.entries(counts).filter((entry): entry is [string, number] => typeof entry[1] === 'number'),
    ),
    gauge: gauge?.current,
    ...(course !== undefined ? { course: { ...course } } : {}),
    notes: judged(frame.notes),
    landmines: judged(frame.landmineNotes),
    invisibleNotes: judged(frame.invisibleNotes),
  };
}
 
/** Where a play takes its time from: the virtual clock, or the host's own (to check the two agree). */
export interface PlayTimeSource {
  now(): number;
  /** The wall-clock time (the domain of `pressedAt`) at `ms`. */
  wallClockAt(ms: number): number;
  at(atMs: number, callback: () => void): () => void;
  run<T>(play: () => Promise<T>): Promise<T>;
}
 
/** Runs a play on a fresh virtual clock. */
export function virtualTime(): PlayTimeSource {
  const clock = createVirtualClock();
  return {
    now: () => clock.now(),
    wallClockAt: (ms) => clock.wallClockNow() - clock.now() + ms,
    at: (atMs, callback) => clock.at(atMs, callback),
    run: (play) => clock.run(play),
  };
}
 
/** Runs a play on the host's clock and timers, in real time. */
export function realTime(): PlayTimeSource {
  const originMs = performance.now();
  return {
    now: () => performance.now() - originMs,
    wallClockAt: (ms) => performance.timeOrigin + originMs + ms,
    at: (atMs, callback) => {
      const handle = setTimeout(callback, Math.max(0, atMs - (performance.now() - originMs)));
      return () => clearTimeout(handle);
    },
    run: (play) => play(),
  };
}
 
const formatMs = (ms: number): string => ms.toFixed(3);
 
const formatNumber = (value: number | undefined): string =>
  value === undefined ? '-' : String(Math.round(value * 1e6) / 1e6);
 
const formatEvent = (event: BeMusicEvent): string =>
  `${event.channel}:${event.value}@${event.measure}+${event.position[0]}/${event.position[1]}`;
 
function createTestAudioSession(
  time: PlayTimeSource,
  options: TestAudioSessionOptions,
  record: (entry: string) => void,
): AudioSession {
  let startedAtMs: number | undefined;
  let pausedAtMs: number | undefined;
  let pausedMs = 0;
  const outputMs = (): number => {
    if (startedAtMs === undefined) return 0;
    const elapsedMs = Math.max(0, (pausedAtMs ?? time.now()) - startedAtMs - pausedMs);
    const quantumMs = options.quantumMs;
    return quantumMs === undefined || !(quantumMs > 0) ? elapsedMs : Math.floor(elapsedMs / quantumMs) * quantumMs;
  };
  const entry = (text: string): void => record(`${formatMs(time.now())} ${text}`);
  return {
    backendLabel: 'characterization',
    chartStartDelayMs: options.chartStartDelayMs ?? 0,
    start: () => {
      startedAtMs = time.now();
      entry('start');
    },
    finish: async () => entry('finish'),
    dispose: async () => entry('dispose'),
    pause: () => {
      pausedAtMs = time.now();
      entry('pause');
    },
    resume: () => {
      Eif (pausedAtMs !== undefined) pausedMs += time.now() - pausedAtMs;
      pausedAtMs = undefined;
      entry('resume');
    },
    ...(options.clock === false
      ? {}
      : {
          getClockState: () => ({
            outputSeconds: outputMs() / 1000,
            scheduledSeconds: (outputMs() + (startedAtMs === undefined ? 0 : (options.writeAheadMs ?? 0))) / 1000,
          }),
        }),
    triggerEvent: (event) => entry(`trigger ${formatEvent(event)}`),
    ...(options.schedulesAhead === true
      ? {
          scheduleEventAt: (event: BeMusicEvent, outputSeconds: number) =>
            entry(`schedule ${formatEvent(event)} @${formatNumber(outputSeconds)}`),
        }
      : {}),
    seek: (seconds) => entry(`seek ${formatNumber(seconds)}`),
    triggerEventAt: (event, offsetSeconds) => entry(`trigger-at ${formatEvent(event)} +${formatNumber(offsetSeconds)}`),
    stopChannel: (channel) => entry(`stop ${channel}`),
    setTempo: (tempo) => entry(`tempo ${tempo}`),
  };
}
 
/** Turns lanes into the input tokens bound to them. */
function laneTokens(context: CreatePlayerInputRuntimeContext, lanes: readonly string[]): string[] {
  return lanes.map((lane) => {
    for (const [token, channels] of context.inputTokenToChannels) {
      if (channels.length === 1 && channels[0] === lane) return token;
    }
    for (const [token, channels] of context.inputTokenToChannels) {
      if (channels.includes(lane)) return token;
    }
    throw new Error(`No input token is bound to lane ${lane}.`);
  });
}
 
function scriptCommands(
  context: CreatePlayerInputRuntimeContext,
  step: ScriptStep,
  wallClockAt: (ms: number) => number,
): PlayerInputCommand[] {
  // Each lane is its own key: its own commands, in the order the keys are listed.
  if ('command' in step) return [step.command];
  if ('commands' in step) return [...step.commands];
  const stamp = step.pressedAtMs === undefined ? {} : { pressedAt: wallClockAt(step.pressedAtMs) };
  if ('down' in step) {
    return laneTokens(context, step.down).flatMap((token): PlayerInputCommand[] => [
      { kind: 'lane-input', tokens: [token], ...stamp },
      { kind: 'kitty-state', pressTokens: [token], repeatTokens: [], releaseTokens: [], ...stamp },
    ]);
  }
  if ('up' in step) {
    return laneTokens(context, step.up).map((token): PlayerInputCommand => ({
      kind: 'kitty-state',
      pressTokens: [],
      repeatTokens: [],
      releaseTokens: [token],
      ...stamp,
    }));
  }
  return laneTokens(context, step.press).map((token): PlayerInputCommand => ({
    kind: 'lane-input',
    tokens: [token],
    ...stamp,
  }));
}
 
/** Runs one play and collects what it showed. */
export async function observePlay(
  play: CharacterizationPlay,
  time: PlayTimeSource = virtualTime(),
): Promise<PlayObservation> {
  const audio: string[] = [];
  const judges: string[] = [];
  const ui: string[] = [];
  const host: string[] = [];
  const log: string[] = [];
  const outputChunks: string[] = [];
  const frames: PlayObservation['frames'] = { count: 0, judged: [] };
  const captured: Record<string, JudgeStateSnapshot> = {};
  const captureAt = [...(play.captureAt ?? [])].sort((a, b) => a - b);
  let pendingCaptures = [...captureAt];
  const now = (): string => formatMs(time.now());
  const hostEntry = (text: string): void => {
    host.push(`${now()} ${text}`);
  };
  let replay: BeMusicReplay | undefined;
  const pendingInputs: Array<() => void> = [];
  const holdController = play.holdAfterChart === undefined ? undefined : new AbortController();
 
  const options: PlayerOptions = {
    leadInMs: 0,
    tui: false,
    ...(play.audio === false
      ? { audio: false }
      : {
          createAudioSession: async () => createTestAudioSession(time, play.audio || {}, (entry) => audio.push(entry)),
        }),
    writeOutput: (text) => {
      outputChunks.push(text);
    },
    onLog: (entry) => {
      const { emittedAtUnixMs: _unix, emittedAtMonotonicMs: _monotonic, ...fields } = entry.fields ?? {};
      log.push(`${now()} ${entry.level} ${entry.event} ${JSON.stringify(fields)}`);
    },
    onLoadComplete: () => hostEntry('load-complete'),
    onTempoChange: (change) => hostEntry(`tempo x${change.tempo} at ${formatNumber(change.seconds)}`),
    onHighSpeedChange: (highSpeed) => hostEntry(`high-speed ${formatNumber(highSpeed)}`),
    onRulesetResolved: (info) =>
      hostEntry(`ruleset ${info.id} ${info.longNoteStyle} note=${JSON.stringify(info.windows.note)}`),
    recordReplay: {},
    onReplayRecorded: (recorded) => {
      replay = recorded;
    },
    createInputRuntime: (context) => {
      hostEntry(`input-runtime create ${context.mode}`);
      // Scripted input is scheduled from the start of the play, whether or not the runtime was started: a host pushes
      // its interrupt and view commands straight onto the bus too.
      for (const step of play.script ?? []) {
        pendingInputs.push(
          time.at(step.atMs, () => {
            for (const input of scriptCommands(context, step, (ms) => time.wallClockAt(ms)))
              context.inputSignals.pushCommand(input);
          }),
        );
      }
      const reportsKeyReleases = play.reportsKeyReleases ?? !(play.script ?? []).some((step) => 'press' in step);
      return {
        start: () => hostEntry('input-runtime start'),
        stop: () => hostEntry('input-runtime stop'),
        ...(reportsKeyReleases ? { reportsKeyReleases } : {}),
      };
    },
    ...(play.ui === false
      ? {}
      : {
          createUIRuntime: async (context: CreatePlayerUIRuntimeContext) => {
            observeUI(context);
            return {
              tuiEnabled: true,
              start: () => hostEntry('ui start'),
              stop: () => hostEntry('ui stop'),
              dispose: () => hostEntry('ui dispose'),
              triggerPoor: (seconds: number) => hostEntry(`ui trigger-poor ${formatNumber(seconds)}`),
              clearPoor: () => hostEntry('ui clear-poor'),
            };
          },
        }),
    ...(holdController === undefined
      ? {}
      : {
          holdAfterChart: {
            signal: holdController.signal,
            onSettled: () => {
              hostEntry('hold settled');
              time.at(time.now() + play.holdAfterChart!.releaseAfterMs, () => {
                hostEntry('hold release');
                holdController.abort();
              });
            },
          },
        }),
    ...play.options,
  };
 
  function observeUI(context: CreatePlayerUIRuntimeContext): void {
    const { stateSignals, uiSignals } = context;
    const publishJudgeCombo = stateSignals.publishJudgeCombo;
    stateSignals.publishJudgeCombo = (judge, combo, channel, updatedAtMs, deltaMs) => {
      const gauge = uiSignals.getFrame().summary.gauge;
      judges.push(
        `${now()} ${judge} combo=${combo}${channel === undefined ? '' : ` ch=${channel}`}` +
          `${deltaMs === undefined ? '' : ` delta=${formatNumber(deltaMs)}`} gauge=${formatNumber(gauge?.current)}`,
      );
      publishJudgeCombo(judge, combo, channel, updatedAtMs, deltaMs);
    };
    const pushCommand = uiSignals.pushCommand;
    uiSignals.pushCommand = (uiCommand: PlayerUICommand) => {
      if (uiCommand.kind === 'seek') {
        const { generation, seconds, snapshot } = uiCommand;
        const last = snapshot.judgments.at(-1);
        ui.push(
          `${now()} seek generation=${generation} seconds=${formatNumber(seconds)} combo=${snapshot.combo}` +
            ` maxCombo=${snapshot.maxCombo} exScore=${snapshot.summary.exScore}` +
            ` gauge=${formatNumber(snapshot.summary.gauge?.current)} judgments=${snapshot.judgments.length}` +
            `${last === undefined ? '' : ` last=${last.judge}@${formatNumber(last.seconds)}#${last.combo}`}`,
        );
        pushCommand(uiCommand);
        return;
      }
      const { kind, ...fields } = uiCommand;
      const details = Object.entries(fields).map(([key, value]) =>
        key === 'channel'
          ? ` ${String(value)}`
          : ` ${key}=${typeof value === 'number' ? formatNumber(value) : String(value)}`,
      );
      ui.push(`${now()} ${kind}${details.join('')}`);
      pushCommand(uiCommand);
    };
    const seen = new Set<PlayerUIFrameNote>();
    let generation = 0;
    const publishFrame = uiSignals.publishFrame;
    uiSignals.publishFrame = (frame) => {
      play.onFrame?.(frame);
      frames.count += 1;
      if ((frame.generation ?? 0) !== generation) {
        generation = frame.generation ?? 0;
        // A seek judges the notes again from the start: each shows as judged anew, and is captured anew.
        seen.clear();
        pendingCaptures = [...captureAt];
        const clock = frame.clock;
        (frames.generations ??= []).push(
          `${now()} generation=${generation} seconds=${formatNumber(frame.currentSeconds)}` +
            (clock === undefined
              ? ''
              : ` output=${formatNumber(clock.outputSeconds)} tempo=${formatNumber(clock.tempo)}` +
                `${clock.paused ? ' paused' : ''}`),
        );
      }
      frames.last =
        `${now()} seconds=${formatNumber(frame.currentSeconds)} beat=${formatNumber(frame.currentBeat)}` +
        `${frame.displayBeat === undefined ? '' : ` displayBeat=${formatNumber(frame.displayBeat)}`}`;
      const scan = (kind: string, notes: readonly PlayerUIFrameNote[] | undefined): void => {
        for (const note of notes ?? []) {
          if (!note.judged || seen.has(note)) continue;
          seen.add(note);
          frames.judged.push(
            `${now()} seconds=${formatNumber(frame.currentSeconds)} ${kind} ${note.channel}@${formatNumber(note.seconds)}`,
          );
        }
      };
      scan('note', frame.notes);
      scan('mine', frame.landmineNotes);
      scan('invisible', frame.invisibleNotes);
      publishFrame(frame);
      while (pendingCaptures.length > 0 && frame.currentSeconds >= pendingCaptures[0]!) {
        const at = pendingCaptures.shift()!;
        captured[formatNumber(at)] = snapshotJudgeState(frame);
      }
    };
  }
 
  const driver = play.driver === 'manual' ? manualPlay : autoPlay;
  let outcome = 'completed';
  let summary: PlayerSummary | undefined;
  try {
    summary = await time.run(() => driver(play.chart, options));
  } catch (error) {
    outcome =
      error instanceof PlayerInterruptedError
        ? `interrupted: ${error.reason}`
        : `error: ${error instanceof Error ? error.message : String(error)}`;
  } finally {
    for (const cancel of pendingInputs) cancel();
  }
  const endedAtMs = time.now();
 
  return {
    outcome,
    endedAtMs: Math.round(endedAtMs * 1000) / 1000,
    ...(summary === undefined ? {} : { summary }),
    ...(replay === undefined ? {} : { replay, ...simulateReadableRulesets(replay) }),
    audio,
    judges,
    ui,
    frames,
    host,
    log,
    ...(play.captureAt === undefined ? {} : { captured }),
    // The HIGH-SPEED hint names the host platform's modifier key (Option on macOS, Alt elsewhere).
    output: outputChunks
      .join('')
      .split('\n')
      .filter((line) => line.length > 0)
      .map((line) => line.replace(/\b(?:Option|Alt)\+/g, '<Alt/Option>+')),
  };
}
 
/** Parts of a play that often repeat an earlier play's of the same case; a repeat is written as a reference. */
const SHARED_PARTS: ReadonlyArray<readonly string[]> = [
  ['replay', 'chart'],
  ['replay', 'inputs'],
  ['replay', 'results'],
  ['simulated'],
  ['log'],
  ['output'],
];
 
/**
 * The snapshot form of the plays of one case: volatile replay fields dropped (`createdAt`, the recorder's engine
 * version), every number rounded to a millionth (so reordering float arithmetic does not churn the snapshots while any
 * real change still shows), and a large part that equals an earlier play's written as `"(same as <play>)"`.
 */
export function snapshotOf(plays: Readonly<Record<string, PlayObservation>>): Record<string, unknown> {
  const result: Record<string, Record<string, unknown>> = {};
  for (const [name, observation] of Object.entries(plays)) {
    const play = roundNumbers(observation) as Record<string, unknown>;
    if (observation.replay !== undefined) {
      const { createdAt: _createdAt, recorder: _recorder, ...replay } = play.replay as Record<string, unknown>;
      play.replay = replay;
    }
    for (const path of SHARED_PARTS) {
      const value = readPath(play, path);
      if (value === undefined) continue;
      const json = JSON.stringify(value);
      const earlier = Object.keys(result).find((other) => JSON.stringify(readPath(result[other]!, path)) === json);
      if (earlier !== undefined) writePath(play, path, `(same as ${earlier})`);
    }
    result[name] = play;
  }
  return result;
}
 
function readPath(value: Record<string, unknown>, path: readonly string[]): unknown {
  let current: unknown = value;
  for (const key of path) {
    if (typeof current !== 'object' || current === null) return undefined;
    current = (current as Record<string, unknown>)[key];
  }
  return typeof current === 'string' && current.startsWith('(same as ') ? undefined : current;
}
 
function writePath(value: Record<string, unknown>, path: readonly string[], replacement: unknown): void {
  let current = value;
  for (const key of path.slice(0, -1)) current = current[key] as Record<string, unknown>;
  current[path.at(-1)!] = replacement;
}
 
function roundNumbers(value: unknown): unknown {
  if (typeof value === 'number') {
    return Number.isInteger(value) ? value : Math.round(value * 1e6) / 1e6 || 0;
  }
  if (Array.isArray(value)) return value.map(roundNumbers);
  if (typeof value !== 'object' || value === null) return value;
  return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, roundNumbers(child)]));
}
 
/** JSON with every object or array that fits in 120 columns on one line, so a snapshot stays short and diffs by line. */
export function formatSnapshot(value: unknown, indent = ''): string {
  const inline = JSON.stringify(value);
  Iif (inline === undefined) return 'null';
  if (typeof value !== 'object' || value === null || indent.length + inline.length <= 120) return inline;
  const inner = `${indent}  `;
  if (Array.isArray(value)) {
    return `[\n${value.map((item) => `${inner}${formatSnapshot(item, inner)}`).join(',\n')}\n${indent}]`;
  }
  const entries = Object.entries(value).filter(([, child]) => child !== undefined);
  const lines = entries.map(([key, child]) => `${inner}${JSON.stringify(key)}: ${formatSnapshot(child, inner)}`);
  return `{\n${lines.join(',\n')}\n${indent}}`;
}
 
/**
 * The recorded log re-simulated under each ruleset that can read it, and why the others cannot: a ruleset that lacks
 * the replay's bare gauge refuses it, as `rejudgeReplay` reports, instead of playing a lookalike.
 */
function simulateReadableRulesets(replay: BeMusicReplay): Pick<PlayObservation, 'simulated' | 'notSimulated'> {
  const simulated: Record<string, ReplayRulesetResult> = {};
  const notSimulated: Record<string, ReplayNotSimulatedReason> = {};
  for (const ruleset of REPLAY_SIMULATOR_RULESETS) {
    const reason = findReplayNotSimulatedReason(replay, ruleset);
    if (reason === undefined) simulated[ruleset] = simulateReplay(replay, { ruleset });
    else notSimulated[ruleset] = reason;
  }
  return { simulated, ...(Object.keys(notSimulated).length === 0 ? {} : { notSimulated }) };
}