ravensight-playtest 0.19.0 → 0.20.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.
@@ -17,6 +17,7 @@
17
17
  import net from 'node:net';
18
18
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
19
19
  import { normalizeView3d } from './view3dState.js';
20
+ import { DEFAULT_TIME_SCALE, slowedObservationLine } from './slowMotion.js';
20
21
 
21
22
  export const PROTOCOL = 1;
22
23
  export const MAX_LINE_BYTES = 65536;
@@ -112,6 +113,14 @@ export function usesHook(facts, { realtime = false } = {}) {
112
113
  && facts.capabilities.includes('pause') && facts.capabilities.includes('advance'));
113
114
  }
114
115
 
116
+ /**
117
+ * Whether a game can be slowed down (contract section 3, `time_scale`): it
118
+ * lists `time_scale` and has a clock mode. A `none` hello lists nothing.
119
+ */
120
+ export function offersTimeScale(facts) {
121
+ return Boolean(facts && facts.pause_mode !== 'none' && facts.capabilities.includes('time_scale'));
122
+ }
123
+
115
124
  /**
116
125
  * Whether a game offers its 3D view (contract section 9): it lists `view3d`
117
126
  * and has a clock mode. A `none` hello lists nothing, so it never does.
@@ -171,11 +180,16 @@ export function framePng(header, chunks) {
171
180
  * @param {Object} options
172
181
  * @param {{token?: string|null, runId?: string|null}} [options.playtest]
173
182
  * @param {boolean} [options.realtime] never pause; only record the hello
183
+ * @param {{mode?: 'auto'|'on'|'off', scale?: number}|null} [options.slowMotion] slow motion (./slowMotion.js):
184
+ * `on` slows the game while the playtester decides from its hello, instead of pausing it; `auto` slows it
185
+ * when `slowDown` is called on a run that does not pause it; `off` never slows it
174
186
  * @param {number} [options.settleMs] game time an action gets before the next observation
175
187
  */
176
188
  export function createTimeControl({
177
189
  playtest = null,
178
190
  realtime = false,
191
+ slowMotion = null,
192
+ now = Date.now,
179
193
  settleMs = SETTLE_MS,
180
194
  keepaliveMs = KEEPALIVE_MS,
181
195
  timeoutMs = DEFAULT_TIMEOUT_MS,
@@ -199,8 +213,21 @@ export function createTimeControl({
199
213
  const pending = new Map();
200
214
  const seenChallenges = new Set();
201
215
  const helloWaiters = new Set();
216
+ // Slow motion (./slowMotion.js). `wanted` is why it was asked for (`flag` or `style`), `slow` the scale the
217
+ // game runs at while the playtester decides once the game took it, `outcome` what the run records. The
218
+ // game's own clock is kept apart from the wall clock: `mark` is where the current slowed stretch began.
219
+ const slowMode = slowMotion && ['auto', 'on', 'off'].includes(slowMotion.mode) ? slowMotion.mode : 'auto';
220
+ const slowScale = slowMotion && Number.isFinite(slowMotion.scale) && slowMotion.scale > 0 && slowMotion.scale <= 1 ? slowMotion.scale : DEFAULT_TIME_SCALE;
221
+ let wanted = slowMode === 'on' ? { reason: 'flag', action: null } : null;
222
+ let slow = null;
223
+ let outcome = null;
224
+ let applying = null;
225
+ let mark = null;
226
+ let slowedGameMs = 0;
227
+ let slowedWallMs = 0;
202
228
 
203
- const engaged = () => Boolean(socket && !failed && usesHook(hello, { realtime }));
229
+ // A game slowed by --time-scale is not paused between decisions: slowing is what the run does instead.
230
+ const engaged = () => Boolean(socket && !failed && !slow && usesHook(hello, { realtime }));
204
231
 
205
232
  function stopKeepalive() {
206
233
  if (keepalive) clearInterval(keepalive);
@@ -279,6 +306,8 @@ export function createTimeControl({
279
306
  socket = conn;
280
307
  const { game_challenge: _drop, ...kept } = facts;
281
308
  hello = kept;
309
+ // Slow motion asked for before the game said hello (--time-scale) starts now, before the first look.
310
+ if (wanted) applying = applySlow();
282
311
  for (const wake of helloWaiters) wake();
283
312
  helloWaiters.clear();
284
313
  } else {
@@ -345,6 +374,62 @@ export function createTimeControl({
345
374
  return state;
346
375
  }
347
376
 
377
+ /** Close the slowed stretch that began at `mark` with the game's clock as `state` gives it. */
378
+ function closeStretch(state) {
379
+ if (!mark || !state || !Number.isFinite(state.clock_ms)) { mark = null; return; }
380
+ slowedGameMs += Math.max(0, state.clock_ms - mark.clock);
381
+ slowedWallMs += Math.max(0, now() - mark.at);
382
+ mark = null;
383
+ }
384
+
385
+ /** Ask the game for a scale; its state, or null when it refused (the channel stays open) or the channel ended. */
386
+ async function setScale(scale) {
387
+ try {
388
+ return await call('time_scale', { scale }, CALL_GRACE_MS);
389
+ } catch (error) {
390
+ if (error && error.code === undefined) drop(error.message);
391
+ return null;
392
+ }
393
+ }
394
+
395
+ /** Slow the connected game down, once, when it can be and the run does not pause it. */
396
+ async function applySlow() {
397
+ if (slow || !wanted) return outcome;
398
+ const base = { reason: wanted.reason, scale: slowScale, ...(Number.isInteger(wanted.action) ? { since_action: wanted.action } : {}) };
399
+ if (!hello || !socket || failed || !offersTimeScale(hello)) {
400
+ outcome = { status: 'not_supported', ...base };
401
+ return outcome;
402
+ }
403
+ // A run that pauses the game between decisions (no --realtime) needs no slow motion unless --time-scale asked for it.
404
+ if (wanted.reason !== 'flag' && usesHook(hello, { realtime })) {
405
+ outcome = { status: 'not_needed', ...base };
406
+ return outcome;
407
+ }
408
+ const state = await setScale(slowScale);
409
+ if (!state) {
410
+ outcome = { status: failed ? 'not_supported' : 'refused', ...base };
411
+ return outcome;
412
+ }
413
+ slow = slowScale;
414
+ mark = { clock: Number.isFinite(state.clock_ms) ? state.clock_ms : 0, at: now() };
415
+ outcome = { status: 'on', ...base };
416
+ return outcome;
417
+ }
418
+
419
+ /** Run one input or wait at the game's own speed, then slow it down again for the next decision. */
420
+ async function atFullSpeed(fn) {
421
+ const state = await setScale(1);
422
+ closeStretch(state);
423
+ try {
424
+ return await fn();
425
+ } finally {
426
+ if (slow && socket && !failed) {
427
+ const again = await setScale(slow);
428
+ if (again) mark = { clock: Number.isFinite(again.clock_ms) ? again.clock_ms : 0, at: now() };
429
+ }
430
+ }
431
+ }
432
+
348
433
  return {
349
434
  /**
350
435
  * Open the listener and return the variables for the game's environment,
@@ -378,8 +463,30 @@ export function createTimeControl({
378
463
  },
379
464
  get engaged() { return engaged(); },
380
465
  get paused() { return paused; },
466
+ /** The share of its speed the game runs at while the playtester decides, or null when it is not slowed. */
467
+ get slowScale() { return slow && socket && !failed ? slow : null; },
468
+ /** The observation line while the game is slowed, or null. */
469
+ timingLine() { return slow && socket && !failed ? slowedObservationLine(slow) : null; },
470
+ /**
471
+ * Slow the game down because of what kind of game it is (the persona loop, once the kind is settled).
472
+ * Returns what the run records: `{status, reason, scale, since_action?}`. `status` is `on`,
473
+ * `not_supported` (no hook or no time_scale), `refused`, `not_needed` (the run pauses the game
474
+ * between decisions) or `switched_off` (--no-slow-motion). Never throws.
475
+ */
476
+ async slowDown({ action = null } = {}) {
477
+ if (applying) await applying;
478
+ if (outcome) return outcome;
479
+ if (slowMode === 'off') {
480
+ outcome = { status: 'switched_off', reason: 'style', scale: slowScale, ...(Number.isInteger(action) ? { since_action: action } : {}) };
481
+ return outcome;
482
+ }
483
+ wanted = { reason: 'style', action: Number.isInteger(action) ? action : null };
484
+ applying = applySlow();
485
+ return applying;
486
+ },
381
487
  /** Freeze the game for the decision gap. No-op without the hook. */
382
488
  async park() {
489
+ if (applying) await applying;
383
490
  if (!engaged() || paused) return false;
384
491
  return pause();
385
492
  },
@@ -389,6 +496,8 @@ export function createTimeControl({
389
496
  * pause again before the next observation. Without it: just the input.
390
497
  */
391
498
  async act(send) {
499
+ if (applying) await applying;
500
+ if (slow && socket && !failed) return atFullSpeed(send);
392
501
  if (!engaged()) return send();
393
502
  stopKeepalive();
394
503
  if (paused) {
@@ -404,6 +513,9 @@ export function createTimeControl({
404
513
  /** A wait action: game time with the hook, real time without. */
405
514
  async wait(ms) {
406
515
  const bounded = Math.min(5000, Math.max(0, Number(ms) || 0));
516
+ if (applying) await applying;
517
+ // Slowed: a wait is game time at full speed, as an input is.
518
+ if (slow && socket && !failed && bounded > 0) { await atFullSpeed(() => sleep(bounded)); return; }
407
519
  if (engaged() && bounded > 0) {
408
520
  if (await advance(bounded)) return;
409
521
  }
@@ -463,6 +575,9 @@ export function createTimeControl({
463
575
  if (closed) return;
464
576
  closed = true;
465
577
  stopKeepalive();
578
+ if (applying) await applying.catch(() => null);
579
+ // The last slowed stretch ends here; the game goes back to its own scale when the channel closes.
580
+ if (socket && slow && mark) closeStretch(await call('state', undefined, 2000).catch(() => null));
466
581
  if (socket && paused) await guarded('resume', undefined, 2000);
467
582
  if (socket) { socket.end(); socket.destroy(); socket = null; }
468
583
  if (server) await new Promise(resolve => server.close(() => resolve()));
@@ -472,10 +587,17 @@ export function createTimeControl({
472
587
  },
473
588
  /** What the run records. Never the nonce. */
474
589
  summary() {
475
- if (!hello) return { hook: false };
590
+ // What slow motion did, when it was asked for. A flag with no game to slow is said as not supported.
591
+ const slowRecord = (outcome || wanted) ? {
592
+ slow_motion: {
593
+ ...(outcome || { status: 'not_supported', reason: wanted.reason, scale: slowScale }),
594
+ ...(slow ? { slowed_game_ms: Math.round(slowedGameMs), slowed_wall_ms: Math.round(slowedWallMs), ...(slowedWallMs > 0 ? { measured_scale: Math.round((slowedGameMs / slowedWallMs) * 1000) / 1000 } : {}) } : {})
595
+ }
596
+ } : {};
597
+ if (!hello) return { hook: false, ...slowRecord };
476
598
  return {
477
599
  hook: true,
478
- used: usesHook(hello, { realtime }),
600
+ used: !slow && usesHook(hello, { realtime }),
479
601
  sdk: hello.sdk,
480
602
  sdk_version: hello.sdk_version,
481
603
  engine: hello.engine,
@@ -485,10 +607,11 @@ export function createTimeControl({
485
607
  auto_resume_refused: autoResumeRefused,
486
608
  ...(offersView3d(hello) ? { view3d: true } : {}),
487
609
  ...(offersFrame(hello) ? { frames: true } : {}),
488
- ...(failed ? { ended: 'channel closed early' } : {})
610
+ ...(failed ? { ended: 'channel closed early' } : {}),
611
+ ...slowRecord
489
612
  };
490
613
  }
491
614
  };
492
615
  }
493
616
 
494
- export default { createTimeControl, parseControlString, checkHello, usesHook, offersView3d, offersFrame, frameHeader, framePng };
617
+ export default { createTimeControl, parseControlString, checkHello, usesHook, offersTimeScale, offersView3d, offersFrame, frameHeader, framePng };
@@ -59,6 +59,7 @@ import os from 'node:os';
59
59
  import { MIN_PASSWORD_CHARS } from '../briefLocal.js';
60
60
  // any-game hook: the run's notebook, control learning, language, kind of game and sound (./anygame/index.js).
61
61
  import { createLocalAnyGame } from './anygame/index.js';
62
+ import { isActionStyle, speedSentence, withSpeedLine } from './slowMotion.js';
62
63
  import { TOOL_TEXT_OTHER, NO_SOUND_OTHER } from './anygame/language.js';
63
64
  import { staleObservationCount } from './context.js';
64
65
 
@@ -457,6 +458,8 @@ export async function runPersona(args) {
457
458
  // video time is measured from it.
458
459
  const recordingStartedAt = typeof driver.recordingStartedAt === 'function' ? driver.recordingStartedAt() : null;
459
460
  await driverStop(driver, outcome, log, play.canceled ? 'canceled' : play.gameEnded ? 'game_crashed' : 'completed', transcript);
461
+ // How fast the game played (./slowMotion.js), for report.md: said only when slow motion was asked for.
462
+ honesty.speedLine = speedSentence(outcome.timeControl || null);
460
463
  if (outcome.videoPath && Number.isFinite(recordingStartedAt)) {
461
464
  honesty.video = { startedAt: recordingStartedAt, file: path.basename(outcome.videoPath), ...(outcome.recording && Number.isFinite(outcome.recording.durationMs) ? { durationMs: outcome.recording.durationMs } : {}) };
462
465
  }
@@ -1038,6 +1041,18 @@ async function playLoop({
1038
1041
  const messages = [];
1039
1042
  let actions = 0;
1040
1043
  let turns = 0;
1044
+ // Slow motion (./slowMotion.js): asked of the driver once, when the playtester has settled the game's kind as an
1045
+ // action game. What the driver answered is kept for the step log and the report; it is never a finding.
1046
+ let slowMotion = null;
1047
+ const slowMotionCheck = async () => {
1048
+ if (slowMotion || !driver || typeof driver.slowDown !== 'function' || !anyGame.genre.settled) return;
1049
+ const digest = anyGame.genre.digest();
1050
+ if (!isActionStyle(digest)) return;
1051
+ slowMotion = { status: 'not_supported', reason: 'style', scale: null };
1052
+ try { slowMotion = (await driver.slowDown({ action: actions })) || slowMotion; } catch { /* the run goes on at the game's own speed */ }
1053
+ transcript.write({ kind: 'slow_motion', at_action: actions, kind_of_game: digest.kind, ...(digest.style2d ? { style: digest.style2d } : {}), ...slowMotion });
1054
+ if (slowMotion.status === 'on') log(`the game is an action game, so it runs at ${Math.round(slowMotion.scale * 100)}% of its speed while the playtester decides from action ${actions} on.`);
1055
+ };
1041
1056
  let quitReason = 'budget_exhausted';
1042
1057
  let quitDetail = '';
1043
1058
  let budgetWarned = false;
@@ -1212,6 +1227,7 @@ async function playLoop({
1212
1227
  }
1213
1228
  }
1214
1229
  turns += 1;
1230
+ await slowMotionCheck();
1215
1231
  if (offeredNow() !== offered) {
1216
1232
  // One request writes the conversation to the cache again (the tools are
1217
1233
  // ahead of everything); it happens once, when the game first looks for a gamepad.
@@ -2075,6 +2091,7 @@ async function playLoop({
2075
2091
  return {
2076
2092
  actionsTaken: actions,
2077
2093
  turns,
2094
+ ...(slowMotion ? { slowMotion } : {}),
2078
2095
  distinctScreens: keeper.distinctScreens,
2079
2096
  wrapUpTurn: wrappingUp,
2080
2097
  gameEnded,
@@ -2562,6 +2579,8 @@ async function reportPhase({
2562
2579
  // [native hooks] Where the run started and how many sessions it played, under the same stamp (./startFrom.js).
2563
2580
  const startLine = honesty && (honesty.start || honesty.sessions) ? startReportLine({ ...(honesty.start || {}), sessions: honesty.sessions || null }) : null;
2564
2581
  if (startLine) markdown = withStartLine(markdown, startLine);
2582
+ // The speed the game played at, when slow motion was asked for (./slowMotion.js). A run at the game's own speed says nothing new.
2583
+ if (honesty && honesty.speedLine) markdown = withSpeedLine(markdown, honesty.speedLine);
2565
2584
  // The in-character section held to the record: a sentence the record or the frames show otherwise is left out, and the
2566
2585
  // record's own fact said instead.
2567
2586
  const heldBack = holdInCharacter(markdown, { families: honesty && honesty.intent ? honesty.intent.families() : [], movedAtAll: couldMove(play.records), turnedAway, repeats: repeatsTurnedAway });
@@ -3559,14 +3578,20 @@ async function driverStop(driver, outcome, log, reason, transcript = null) {
3559
3578
  const stopped = await driver.stop({ reason });
3560
3579
  if (stopped?.recording) outcome.recording = stopped.recording;
3561
3580
  // The SDK pause hook (./pauseHook.js): what the game said, never the nonce.
3562
- if (stopped?.timeControl) {
3563
- outcome.timeControl = stopped.timeControl;
3581
+ // Slow motion asked of a driver with no pause hook channel at all (a bridge that did not opt in) is still said.
3582
+ const timeControl = stopped?.timeControl
3583
+ ? stopped.timeControl
3584
+ : outcome.slowMotion ? { hook: false, slow_motion: outcome.slowMotion } : null;
3585
+ if (timeControl) {
3586
+ outcome.timeControl = timeControl;
3564
3587
  // Into the uploaded step log too, so the report can say whether the game was paused (the summary never holds the nonce).
3565
3588
  if (transcript && typeof transcript.write === 'function') {
3566
- try { transcript.write({ kind: 'time_control', ...stopped.timeControl }); } catch { /* the step log is closed: the outcome still has it */ }
3589
+ try { transcript.write({ kind: 'time_control', ...timeControl }); } catch { /* the step log is closed: the outcome still has it */ }
3567
3590
  }
3568
- if (stopped.timeControl.used) log(`the game's SDK paused it between decisions (${stopped.timeControl.pause_mode}; unscaled time ${String(stopped.timeControl.unscaled_time).replace('_', ' ')}${stopped.timeControl.auto_resumed ? `; resumed on its own ${stopped.timeControl.auto_resumed} times` : ''}${stopped.timeControl.auto_resume_refused ? `; the game's own handler refused ${stopped.timeControl.auto_resume_refused} of those resumes, so it may have stayed frozen` : ''}).`);
3569
- else if (stopped.timeControl.hook && stopped.timeControl.pause_mode === 'none') log("the game's SDK offered the pause hook but the game registered no time handler, so it ran in real time.");
3591
+ if (timeControl.used) log(`the game's SDK paused it between decisions (${timeControl.pause_mode}; unscaled time ${String(timeControl.unscaled_time).replace('_', ' ')}${timeControl.auto_resumed ? `; resumed on its own ${timeControl.auto_resumed} times` : ''}${timeControl.auto_resume_refused ? `; the game's own handler refused ${timeControl.auto_resume_refused} of those resumes, so it may have stayed frozen` : ''}).`);
3592
+ else if (timeControl.hook && timeControl.pause_mode === 'none') log("the game's SDK offered the pause hook but the game registered no time handler, so it ran in real time.");
3593
+ const speed = speedSentence(timeControl);
3594
+ if (speed) log(speed);
3570
3595
  }
3571
3596
  if (stopped && stopped.videoPath) outcome.videoPath = stopped.videoPath;
3572
3597
  // A default recording that could not be made here is said once, with why.
package/src/run/replay.js CHANGED
@@ -84,7 +84,7 @@ function divergence(step, frame, expected, actual) {
84
84
  * @param {(options: Object) => Object} [input.makeDriver] - test seam
85
85
  * @returns {Promise<Object>} the simulation replay's result shape, plus counts
86
86
  */
87
- export async function replayTrace({ text, projectDir, godotPath, headless, runDir, signal, env, extraEnv = null, start = null, makeDriver = options => new GodotDriver(options) }) {
87
+ export async function replayTrace({ text, projectDir, godotPath, headless, runDir, signal, env, extraEnv = null, start = null, launchArgs = [], makeDriver = options => new GodotDriver(options) }) {
88
88
  const trace = parseTrace(text);
89
89
  const { header, boot, steps } = trace;
90
90
  const driver = makeDriver({
@@ -101,6 +101,8 @@ export async function replayTrace({ text, projectDir, godotPath, headless, runDi
101
101
  ...(extraEnv && Object.keys(extraEnv).length ? { extraEnv } : {}),
102
102
  // A run that started from a save or a start spec is replayed from the same start.
103
103
  ...(start ? { start } : {}),
104
+ // The same launch arguments as the run (--launch-arg), or as its trace header kept them.
105
+ ...(launchArgs && launchArgs.length ? { launchArgs } : Array.isArray(header.launch_args) && header.launch_args.length ? { launchArgs: header.launch_args.map(String) } : {}),
104
106
  });
105
107
  const result = {
106
108
  matched: true,
@@ -319,7 +319,7 @@ export async function replayFindings({ report, index = [], traceSteps = new Map(
319
319
  if (signal) signal.addEventListener('abort', onAbort, { once: true });
320
320
  let result;
321
321
  try {
322
- result = await replay({ text: prefix, projectDir: driver.projectDir, godotPath: driver.godotPath, headless: driver.headless, runDir: path.join(runDirectory, '.replay'), signal: timer.signal, ...(driver.env ? { env: driver.env } : {}), ...(driver.extraEnv && Object.keys(driver.extraEnv).length ? { extraEnv: driver.extraEnv } : {}), ...(driver.start ? { start: driver.start } : {}) });
322
+ result = await replay({ text: prefix, projectDir: driver.projectDir, godotPath: driver.godotPath, headless: driver.headless, runDir: path.join(runDirectory, '.replay'), signal: timer.signal, ...(driver.env ? { env: driver.env } : {}), ...(driver.extraEnv && Object.keys(driver.extraEnv).length ? { extraEnv: driver.extraEnv } : {}), ...(driver.start ? { start: driver.start } : {}), ...(Array.isArray(driver.launchArgs) && driver.launchArgs.length ? { launchArgs: driver.launchArgs } : {}) });
323
323
  } catch (error) {
324
324
  problem = timer.signal.aborted ? 'the replay ran out of its time' : `a replay could not finish (${String(error && error.message ? error.message : error).slice(0, 80)})`;
325
325
  break;
@@ -379,8 +379,15 @@ export function traceWebInputs(driver, { fingerprint }) {
379
379
  const trace = [];
380
380
  if (!driver || typeof driver.act !== 'function' || typeof driver.screenProbe !== 'function') return trace;
381
381
  const act = driver.act.bind(driver);
382
+ // A replay starts the game once, so the trace ends where a new session started the game again (./sessions.js).
383
+ let ended = false;
384
+ if (typeof driver.relaunch === 'function') {
385
+ const relaunch = driver.relaunch.bind(driver);
386
+ driver.relaunch = async (...args) => { ended = true; return relaunch(...args); };
387
+ }
382
388
  driver.act = async action => {
383
389
  const result = await act(action);
390
+ if (ended) return result;
384
391
  let print = null;
385
392
  try { print = fingerprint(await driver.screenProbe()); } catch { print = null; }
386
393
  trace.push({ action, ok: Boolean(result) && result.ok !== false && !result.refused, changed: result ? result.changed : null, print, ...(result && result.refused === 'avoided' ? { avoided: true } : {}) });
package/src/run/resume.js CHANGED
@@ -239,6 +239,8 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
239
239
  driverMode: journal.options?.driverMode || (MOBILE_DRIVERS.includes(driverName) ? 'webdriver' : undefined),
240
240
  nativePlan: journal.options?.nativePlan || null,
241
241
  realtime: journal.options?.realtime, phone: journal.options?.phone,
242
+ // Slow motion as the run asked (./slowMotion.js).
243
+ timeScale: journal.options?.timeScale, noSlowMotion: journal.options?.noSlowMotion,
242
244
  controller: journal.options?.controller || options.controller || 'standard',
243
245
  controllers,
244
246
  recordVideo: options.recordVideo ?? journal.options?.recordVideo,
@@ -250,6 +252,8 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
250
252
  // The run's start and sessions, as the journal kept them: a resumed run starts where the paid one did.
251
253
  ...(journal.options?.startFrom && typeof journal.options.startFrom === 'object' ? { startFrom: journal.options.startFrom } : {}),
252
254
  ...(Number.isSafeInteger(journal.options?.sessions) ? { sessions: journal.options.sessions } : {}),
255
+ // A Godot run's launch arguments, as the journal kept them (a native desktop run keeps its own in nativePlan).
256
+ ...(Array.isArray(journal.options?.launchArgs) ? { launchArg: journal.options.launchArgs.map(String) } : {}),
253
257
  concurrency: options.concurrency ?? (journal.options && journal.options.concurrency),
254
258
  uploadVideo: options.uploadVideo ?? (journal.options && journal.options.uploadVideo),
255
259
  uploadTranscript: options.uploadTranscript ?? (journal.options && journal.options.uploadTranscript),
@@ -3,7 +3,9 @@
3
3
  * the way a player closes it, started again on the same saved data, and play
4
4
  * goes on, two or three times in one run. docs/hosted-direct/NATIVE_GPU_PLAN.md
5
5
  * section 6 ("Multi-session runs") in the platform repository is the design;
6
- * this is its local half for `godot_driver`, `android_driver` and `ios_driver`.
6
+ * this is its local half for `godot_driver`, `android_driver`, `ios_driver`
7
+ * and the desktop drivers on a Mac (`desktop_driver`, `unity_driver`,
8
+ * `unreal_driver`).
7
9
  *
8
10
  * The rules, stated once:
9
11
  *
@@ -16,8 +18,11 @@
16
18
  * a budget too small for that is refused before the price.
17
19
  * - **The playtester remembers; the game keeps only what it saved.** The
18
20
  * conversation, its notes and the run's notebook carry over. The game is
19
- * given a close request (Godot) or sent to the background (mobile) so a
20
- * game that saves on quit or on pause saves, and then starts cold. A
21
+ * given a close request (Godot), Command-Q (a desktop game on a Mac, then
22
+ * a polite stop signal if it does not quit) or sent to the background
23
+ * (mobile) so a game that saves on quit or on pause saves, and then starts
24
+ * cold. A desktop game plays every session in a home folder of the run's
25
+ * own (./drivers/desktop/runHome.js), so what it saved is there next time. A
21
26
  * playtester told a session is ending is asked to save the way a player
22
27
  * would, a turn ahead.
23
28
  * - **A game that does not start again is a finding.** The run ends there and
@@ -32,7 +37,7 @@ import { runnerFinding, stepsBefore } from './honesty.js';
32
37
  export const MAX_SESSIONS = 3;
33
38
  export const MIN_ACTIONS_PER_SESSION = 10;
34
39
  /** The drivers that can close and start a game again on the same data. */
35
- export const SESSION_DRIVERS = Object.freeze(['godot_driver', 'android_driver', 'ios_driver']);
40
+ export const SESSION_DRIVERS = Object.freeze(['godot_driver', 'android_driver', 'ios_driver', 'desktop_driver', 'unity_driver', 'unreal_driver']);
36
41
  /** How far ahead of a session's end the playtester is told, as a share of one session. */
37
42
  export const WARN_AHEAD_SHARE = 0.2;
38
43
 
@@ -48,7 +53,7 @@ export function sessionProblems(options = {}, driverName = '') {
48
53
  if (options.sessions === undefined) return [];
49
54
  const n = options.sessions;
50
55
  if (!Number.isSafeInteger(n) || n < 1 || n > MAX_SESSIONS) return [`Choose --sessions as 1, 2 or 3.`];
51
- if (n > 1 && !SESSION_DRIVERS.includes(driverName)) return [`--sessions plays a native game across launches (Godot, an Android emulator or an iOS simulator), and this run uses ${driverName || 'no driver'}.`];
56
+ if (n > 1 && !SESSION_DRIVERS.includes(driverName)) return [`--sessions plays a native game across launches (Godot, a desktop game on this Mac, an Android emulator or an iOS simulator), and this run uses ${driverName || 'no driver'}.`];
52
57
  return [];
53
58
  }
54
59
 
@@ -147,7 +152,7 @@ export async function sessionTurn({ sessions, driver, actions, playedSeconds, tr
147
152
  }
148
153
  const session = sessions.began();
149
154
  const observation = await driver.observe().catch(() => null);
150
- transcript.write({ kind: 'session_start', session, of: due.of, actions, relaunch_ms: Date.now() - began, scene: relaunched && relaunched.scene ? String(relaunched.scene).slice(0, 200) : null, saved_files: relaunched && Number.isInteger(relaunched.files) ? relaunched.files : null });
155
+ transcript.write({ kind: 'session_start', session, of: due.of, actions, relaunch_ms: Date.now() - began, scene: relaunched && relaunched.scene ? String(relaunched.scene).slice(0, 200) : null, saved_files: relaunched && Number.isInteger(relaunched.files) ? relaunched.files : null, ...(relaunched && typeof relaunched.closed === 'string' ? { closed: relaunched.closed.slice(0, 40) } : {}) });
151
156
  log(`session ${session} of ${due.of}: the game was closed and started again after ${actions} action(s).`);
152
157
  return { aside: sessionResumedAside({ session, of: due.of, scene: relaunched && relaunched.scene }), observation, session };
153
158
  }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Slow motion through the SDK pause hook's `time_scale` (the platform's
3
+ * docs/playtest/PAUSE_HOOK_CONTRACT.md, sections 3 and 6).
4
+ *
5
+ * A model takes a second or more to decide. A game whose clock keeps running
6
+ * through that gap plays an action game far faster than the playtester can
7
+ * answer it. The pause hook already freezes the game between decisions by
8
+ * default, and then the decision costs no game time at all, so slow motion is
9
+ * not needed. It is for a run where the game keeps running while the
10
+ * playtester decides:
11
+ *
12
+ * - `--realtime` on an action game (a twitch, first person, third person or
13
+ * vehicle game, or a shoot em up, twin stick, fighting or racing style): the
14
+ * game runs at a quarter of its speed while the playtester decides, once the
15
+ * playtester has said what kind of game it is.
16
+ * - `--time-scale <n>` on any game: the game runs at that share of its speed
17
+ * while the playtester decides, from the first frame, instead of being
18
+ * paused. A game whose hook cannot slow it is paused as before.
19
+ * - `--no-slow-motion` keeps `--realtime` at full speed for every game.
20
+ *
21
+ * Inputs and waits always play at the game's own speed (the runner sets the
22
+ * scale back to 1 for them), so a held key or a 2 second wait is the game time
23
+ * the playtester asked for. Only the decision gap is slowed. The video and the
24
+ * step log stay in real time: the runner never rescales a timestamp, and it
25
+ * keeps the game's own clock apart (`slowed_game_ms` against `slowed_wall_ms`).
26
+ *
27
+ * A game that cannot be slowed (no hook, a hook without `time_scale`, a game
28
+ * that refuses the scale) plays at its normal speed and the report says so.
29
+ * That is a limit of the runner and the game's SDK set up, never a finding.
30
+ */
31
+
32
+ /** The share of its speed a game runs at while the playtester decides, by default. */
33
+ export const DEFAULT_TIME_SCALE = 0.25;
34
+ /** The bounds of `--time-scale`. Full speed is `--realtime`; slower than a tenth makes a run crawl. */
35
+ export const MIN_TIME_SCALE = 0.1;
36
+ export const MAX_TIME_SCALE = 0.9;
37
+
38
+ /** The drivers that reach a game's SDK pause hook (../commands/run.js driverOptions). */
39
+ export const HOOK_DRIVERS = Object.freeze(['desktop_driver', 'unity_driver', 'unreal_driver', 'cli_stdio', 'android_driver', 'ios_driver']);
40
+
41
+ /** Kinds of game (./anygame/genre.js) played in real time, where a second of thinking matters. Rhythm is left out: slowing a song breaks it. */
42
+ export const ACTION_KINDS = Object.freeze(['twitch', 'first_person', 'third_person', 'vehicle']);
43
+ /** 2D styles (./anygame/genre2d.js) that are real-time action. */
44
+ export const ACTION_STYLES = Object.freeze(['shmup', 'twin_stick', 'fighting', 'racing']);
45
+
46
+ /**
47
+ * Whether a settled kind and style is an action game that slow motion helps.
48
+ *
49
+ * @param {{kind?: string|null, style2d?: string|null}|null} digest the genre's digest
50
+ * @returns {boolean}
51
+ */
52
+ export function isActionStyle(digest) {
53
+ if (!digest || typeof digest !== 'object') return false;
54
+ if (digest.kind === 'rhythm') return false;
55
+ return ACTION_KINDS.includes(digest.kind) || ACTION_STYLES.includes(digest.style2d);
56
+ }
57
+
58
+ /**
59
+ * What a run asked for: `mode` is `auto` (slow an action game on a run that
60
+ * keeps the game running), `on` (`--time-scale`) or `off` (`--no-slow-motion`).
61
+ *
62
+ * @param {{timeScale?: number, noSlowMotion?: boolean}} options
63
+ * @returns {{mode: 'auto'|'on'|'off', scale: number}}
64
+ */
65
+ export function slowMotionPlan(options = {}) {
66
+ if (options && options.noSlowMotion === true) return { mode: 'off', scale: DEFAULT_TIME_SCALE };
67
+ if (options && options.timeScale !== undefined && validScale(options.timeScale)) return { mode: 'on', scale: options.timeScale };
68
+ return { mode: 'auto', scale: DEFAULT_TIME_SCALE };
69
+ }
70
+
71
+ const validScale = value => typeof value === 'number' && Number.isFinite(value) && value >= MIN_TIME_SCALE && value <= MAX_TIME_SCALE;
72
+
73
+ /**
74
+ * What is wrong with `--time-scale` and `--no-slow-motion`, one sentence each.
75
+ *
76
+ * @param {Object} options
77
+ * @param {string} driverName
78
+ * @returns {string[]}
79
+ */
80
+ export function slowMotionProblems(options = {}, driverName = '') {
81
+ const problems = [];
82
+ const asked = options.timeScale !== undefined;
83
+ if (asked && !validScale(options.timeScale)) problems.push(`Choose --time-scale from ${MIN_TIME_SCALE} to ${MAX_TIME_SCALE}, the share of its speed the game runs at while the playtester decides (0.25 is a quarter). For full speed pass --realtime.`);
84
+ if (asked && options.noSlowMotion === true) problems.push('Pass --time-scale or --no-slow-motion, not both.');
85
+ if ((asked || options.noSlowMotion === true) && driverName && !HOOK_DRIVERS.includes(driverName)) {
86
+ problems.push(`${asked ? '--time-scale' : '--no-slow-motion'} slows a game through its Ravensight SDK's pause hook, which ${HOOK_DRIVERS.join(', ')} reach, and this run uses ${driverName}.`);
87
+ }
88
+ return problems;
89
+ }
90
+
91
+ /** A scale in plain words: "a quarter of its speed", "half its speed", "40% of its speed". */
92
+ export function speedWords(scale) {
93
+ if (!(typeof scale === 'number' && Number.isFinite(scale) && scale > 0)) return 'its normal speed';
94
+ if (Math.abs(scale - 0.25) < 1e-9) return 'a quarter of its speed';
95
+ if (Math.abs(scale - 0.5) < 1e-9) return 'half its speed';
96
+ if (Math.abs(scale - 0.75) < 1e-9) return 'three quarters of its speed';
97
+ return `${Math.round(scale * 100)}% of its speed`;
98
+ }
99
+
100
+ /** The line a driver adds to each observation while the game is slowed. */
101
+ export function slowedObservationLine(scale) {
102
+ return `The game runs at ${speedWords(scale)} while you decide, and at its full speed while your inputs and waits play.`;
103
+ }
104
+
105
+ const seconds = ms => `${Math.round(ms / 100) / 10} s`;
106
+
107
+ /**
108
+ * The sentence the run's report and log carry about the game's speed, or null
109
+ * when nothing was asked of slow motion. Plain words; never a finding.
110
+ *
111
+ * @param {Object|null} timeControl the time control summary (./pauseHook.js)
112
+ * @returns {string|null}
113
+ */
114
+ export function speedSentence(timeControl) {
115
+ const slow = timeControl && timeControl.slow_motion;
116
+ if (!slow || typeof slow !== 'object') return null;
117
+ const why = slow.reason === 'flag' ? 'as --time-scale asked' : 'because it is an action game';
118
+ switch (slow.status) {
119
+ case 'on': {
120
+ const measured = Number.isFinite(slow.slowed_wall_ms) && slow.slowed_wall_ms >= 1000 && Number.isFinite(slow.slowed_game_ms)
121
+ ? ` The game's own clock moved ${seconds(slow.slowed_game_ms)} in ${seconds(slow.slowed_wall_ms)} of those decisions.` : '';
122
+ return `Played at ${speedWords(slow.scale)} while the playtester decided, ${why}, so the playtester could keep up. Inputs and waits played at full speed, and the video is in real time.${measured}`;
123
+ }
124
+ case 'not_supported':
125
+ return `The game's Ravensight SDK did not offer slow motion (the pause hook's time scale), so it played at its normal speed${timeControl.used ? ' and was paused between decisions instead' : ''}.`;
126
+ case 'refused':
127
+ return `The game refused slow motion when the run asked for it, so it played at its normal speed${timeControl.used ? ' and was paused between decisions instead' : ''}.`;
128
+ case 'not_needed':
129
+ return 'The game was paused while the playtester decided, so it did not need slow motion.';
130
+ case 'switched_off':
131
+ return 'Slow motion was switched off for this run (--no-slow-motion), so the game played at its normal speed while the playtester decided.';
132
+ default:
133
+ return null;
134
+ }
135
+ }
136
+
137
+ /** The line report.md carries when the run says how fast the game played. */
138
+ export const SPEED_LABEL = '**Game speed:**';
139
+
140
+ /** report.md with the speed line after the generated-at, played and start lines. */
141
+ export function withSpeedLine(markdown, line) {
142
+ const lines = String(markdown || '').split('\n').filter(entry => !entry.startsWith(SPEED_LABEL));
143
+ if (!line) return lines.join('\n');
144
+ let where = -1;
145
+ lines.forEach((entry, index) => { if (/^\*\*(Generated at|What was played|Where this run started):\*\*/.test(entry)) where = index + 1; });
146
+ if (where === -1) { const heading = lines.findIndex(entry => /^# /.test(entry)); where = heading !== -1 ? heading + 1 : 0; }
147
+ lines.splice(where, 0, `${SPEED_LABEL} ${line}`);
148
+ return lines.join('\n');
149
+ }
150
+
151
+ export default { SPEED_LABEL, withSpeedLine, DEFAULT_TIME_SCALE, MIN_TIME_SCALE, MAX_TIME_SCALE, HOOK_DRIVERS, ACTION_KINDS, ACTION_STYLES, isActionStyle, slowMotionPlan, slowMotionProblems, speedWords, slowedObservationLine, speedSentence };