ravensight-playtest 0.9.0 → 0.10.1

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 (67) hide show
  1. package/README.md +266 -44
  2. package/addons/ravensight_driver/driver.gd +704 -21
  3. package/docs/ADAPTERS.md +11 -7
  4. package/docs/NATIVE_RUNNER.md +3 -1
  5. package/docs/godot-driver.md +136 -13
  6. package/package.json +8 -6
  7. package/src/api/client.js +4 -3
  8. package/src/cli.js +114 -13
  9. package/src/commands/check.js +30 -4
  10. package/src/commands/fakeCore.js +14 -2
  11. package/src/commands/hosted.js +18 -4
  12. package/src/commands/init.js +17 -1
  13. package/src/commands/run.js +209 -14
  14. package/src/commands/upload.js +6 -2
  15. package/src/commands/validate.js +1 -1
  16. package/src/commands/validateHosted.js +50 -5
  17. package/src/config.js +33 -2
  18. package/src/hosted/archivePreflight.js +7 -7
  19. package/src/hosted/buildUpload.js +89 -8
  20. package/src/hosted/recordedRun.js +40 -1
  21. package/src/run/actionSelector.js +14 -3
  22. package/src/run/aggregate.js +57 -3
  23. package/src/run/anygame/controlbook.js +179 -0
  24. package/src/run/anygame/genre.js +179 -0
  25. package/src/run/anygame/index.js +258 -0
  26. package/src/run/anygame/language.js +336 -0
  27. package/src/run/anygame/memory.js +330 -0
  28. package/src/run/anygame/shared-hashes.json +10 -0
  29. package/src/run/anygame/shared.js +24 -0
  30. package/src/run/anygame/sound.js +342 -0
  31. package/src/run/args.js +75 -8
  32. package/src/run/captureCheck.js +161 -0
  33. package/src/run/choiceCheck.js +312 -0
  34. package/src/run/claimGate.js +236 -0
  35. package/src/run/context.js +254 -13
  36. package/src/run/drivers/godot-observation.js +93 -6
  37. package/src/run/drivers/godot.js +769 -46
  38. package/src/run/drivers/recording.js +24 -4
  39. package/src/run/drivers/web.js +1242 -77
  40. package/src/run/edgePass.js +731 -0
  41. package/src/run/fixLoop.js +5 -4
  42. package/src/run/focus.js +65 -0
  43. package/src/run/gamepad.js +108 -0
  44. package/src/run/godotEdgePass.js +235 -0
  45. package/src/run/godotTesterProbes.js +192 -0
  46. package/src/run/headings.js +21 -0
  47. package/src/run/honesty.js +642 -0
  48. package/src/run/inputs.js +256 -0
  49. package/src/run/marks.js +142 -0
  50. package/src/run/personaLoop.js +1128 -120
  51. package/src/run/phone.js +7 -0
  52. package/src/run/pixels.js +215 -0
  53. package/src/run/playClock.js +162 -0
  54. package/src/run/readiness.js +585 -0
  55. package/src/run/refusal.js +67 -0
  56. package/src/run/regions.js +119 -0
  57. package/src/run/report.js +14 -2
  58. package/src/run/reportChecks.js +487 -0
  59. package/src/run/resume.js +3 -2
  60. package/src/run/screenshots.js +161 -0
  61. package/src/run/strip.js +114 -0
  62. package/src/run/testerLedger.js +312 -0
  63. package/src/run/testerProbes.js +584 -0
  64. package/src/run/thinRun.js +102 -0
  65. package/src/run/timeFreeze.js +79 -0
  66. package/src/run/tools.js +454 -29
  67. package/src/runDefaults.js +1 -0
@@ -469,8 +469,11 @@ export function fakeCore({
469
469
  */
470
470
  export function fakeDriver() {
471
471
  let step = 0;
472
+ let runDir = null;
472
473
  return {
473
- async launch() {},
474
+ async launch(options) {
475
+ runDir = options && options.runDir;
476
+ },
474
477
  async observe() {
475
478
  step += 1;
476
479
  return { step, text: 'the title screen of a small game about bunnies', url: 'http://game.test/', elapsedMs: 1 };
@@ -479,7 +482,16 @@ export function fakeDriver() {
479
482
  return { ok: true, changed: true };
480
483
  },
481
484
  async screenshot(name) {
482
- return { path: `/tmp/${name}.png`, relativePath: `screenshots/01-${name}.png` };
485
+ const relativePath = `screenshots/01-${name}.png`;
486
+ // A picture on disk, so the claim checks after the report have one to be shown.
487
+ if (runDir) {
488
+ const { mkdir, writeFile } = await import('node:fs/promises');
489
+ const { join, dirname } = await import('node:path');
490
+ await mkdir(dirname(join(runDir, relativePath)), { recursive: true });
491
+ await writeFile(join(runDir, relativePath), `png ${name}`);
492
+ return { path: join(runDir, relativePath), relativePath };
493
+ }
494
+ return { path: `/tmp/${name}.png`, relativePath };
483
495
  },
484
496
  async consoleErrors() {
485
497
  return [];
@@ -9,7 +9,7 @@ import { quoteHostedRun, runHostedQuote, hostedQuoteLines, prepareHostedRun, adm
9
9
  import { hostedPlaytestStatus, modeOutcomes, modeLine, TERMINAL_PHASES, queueInfo, queueLine } from '../hosted/status.js';
10
10
  import { jobLink } from '../dashboard.js';
11
11
  import { ALWAYS_INCLUDED_PERSONA, hostedPersonas } from '../runDefaults.js';
12
- import { focusFor } from '../hosted/recordedRun.js';
12
+ import { focusFor, uploadSave } from '../hosted/recordedRun.js';
13
13
 
14
14
  /** --tier, --minutes, --start, --focus and --avoid as the quote request takes them. */
15
15
  export function scopeFrom(flags = {}) {
@@ -19,6 +19,19 @@ export function scopeFrom(flags = {}) {
19
19
  ...(named ? { focus: focusFor({ start: flags.start, focus: flags.focus || [], avoid: flags.avoid || [] }) } : {}) };
20
20
  }
21
21
 
22
+ /**
23
+ * The scope with --save: the save file is uploaded first (free), and the quote
24
+ * names it by the id the server gave it. --save-target says where the game
25
+ * reads it; without one the game reads it through the playtest save hook.
26
+ */
27
+ export async function scopeWithSave(flags = {}, { api, gameId, upload = uploadSave } = {}) {
28
+ const scope = scopeFrom(flags);
29
+ if (flags.saveTarget !== undefined && flags.save === undefined) throw new CliError('--save-target says where a save file goes. Name the file with --save. Nothing was charged.');
30
+ if (flags.save === undefined) return scope;
31
+ const save = await upload({ api, gameId, file: flags.save, target: flags.saveTarget });
32
+ return { ...scope, focus: { ...(scope.focus || focusFor({})), save: { saveId: save.saveId } } };
33
+ }
34
+
22
35
  /** The personas a cloud playtest asks for: fresh-eyes plus --personas (and the older --persona). */
23
36
  export function personasFrom(flags = {}) {
24
37
  const named = [flags.personas, flags.persona].filter(Boolean).join(',');
@@ -31,9 +44,10 @@ export async function hostedQuote(flags = {}, deps = {}) {
31
44
  // match: fresh-eyes always, plus any named.
32
45
  const personas = personasFrom(flags);
33
46
  return withAuthHandling(context, async () => {
47
+ const gameId = resolveGameId(flags, context.config);
34
48
  const result = await quoteHostedRun({ api: context.api, apiUrl: context.api.apiUrl,
35
- gameId: resolveGameId(flags, context.config), buildId: flags.build, profileVersion: flags.profile,
36
- personas, ...scopeFrom(flags),
49
+ gameId, buildId: flags.build, profileVersion: flags.profile,
50
+ personas, ...await scopeWithSave(flags, { api: context.api, gameId, upload: deps.uploadSave }),
37
51
  standardProvider: flags.geriProvider ? GERI_PROVIDERS[flags.geriProvider] : flags.standardProvider, includeVideo: Boolean(flags.video),
38
52
  output: flags.output });
39
53
  if (flags.json) ui.json({ ...result, personas });
@@ -184,7 +198,7 @@ export async function hostedRunDirect(flags = {}, deps = {}) {
184
198
  const api = context.api, apiUrl = api.apiUrl, gameId = resolveGameId(flags, context.config);
185
199
  await assertNoUnknownAdmission({ repoRoot: context.repoRoot, apiUrl, gameId, evenIfUnknown: Boolean(flags.evenIfUnknown) });
186
200
  const { offer, build, funding } = await prepareHostedRun({ api, apiUrl, gameId, buildId: flags.build,
187
- personas: personasFrom(flags), ...scopeFrom(flags), includeVideo: Boolean(flags.video), now });
201
+ personas: personasFrom(flags), ...await scopeWithSave(flags, { api, gameId, upload: deps.uploadSave }), includeVideo: Boolean(flags.video), now });
188
202
  if (!flags.json) {
189
203
  ui.info(`Build ${build.buildId}${build.entrypoint ? ` (${build.entrypoint})` : ''}${flags.build ? '' : ', the newest ready build'}.`);
190
204
  hostedQuoteLines(offer).forEach(line => ui.info(line));
@@ -1,7 +1,7 @@
1
1
  import { appendFile, readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { createContext } from '../api/index.js';
4
- import { defaultConfig, loadConfig, saveConfig } from '../config.js';
4
+ import { defaultConfig, loadConfig, saveConfig, stepLogSetting, stepLogUploadsLine } from '../config.js';
5
5
  import { withAuthHandling } from '../auth/session.js';
6
6
  import { paths } from '../paths.js';
7
7
  import { ui } from '../ui/index.js';
@@ -144,6 +144,8 @@ async function linkRepo(context, flags, repoRoot, choose, recommend) {
144
144
  concurrency: machine.recommended,
145
145
  ...(godot ? { driver: 'godot_driver', build: { kind: 'godot_project', ref: '.' } } : {})
146
146
  }),
147
+ // A relink keeps the uploads the project already chose; only a fresh link writes the default.
148
+ ...(existing && existing.uploads && typeof existing.uploads === 'object' ? { uploads: existing.uploads } : {}),
147
149
  api_url: context.apiUrl
148
150
  },
149
151
  { repoRoot }
@@ -160,9 +162,23 @@ async function linkRepo(context, flags, repoRoot, choose, recommend) {
160
162
  ui.info(`Wrote ${paths.configFile({ repoRoot })}`);
161
163
  if (godot) ui.info('This is a Godot project, so runs use godot_driver on this directory.');
162
164
  ui.info(`Concurrency ${config.concurrency}, from this machine (${machine.cpus} logical cpus, ${machine.freeMemGb} GB free).`);
165
+ ui.info(stepLogInitLine(config));
163
166
  if (gitignore === 'added') ui.info(`Added ${GITIGNORE_LINES.join(' and ')} to .gitignore`);
164
167
  if (gitignore === 'absent') ui.warn(`No .gitignore here. Add ${GITIGNORE_LINES.join(' and ')} to whatever ignores build output.`);
165
168
  ui.blank();
166
169
  ui.info('Next: ravensight-playtest brief');
167
170
  return ExitCode.OK;
168
171
  }
172
+
173
+ /**
174
+ * What init tells the developer about the step log, once: that a persona run
175
+ * uploads it and how to stop that, or that this project keeps it local.
176
+ * @param {Object} config the config init wrote
177
+ * @returns {string}
178
+ */
179
+ export function stepLogInitLine(config) {
180
+ if (stepLogSetting(config).upload === false) {
181
+ return 'A persona run\'s step log (transcript.jsonl) stays on this machine ("uploads": { "step_log": false } in .ravensight/config.json), so the dashboard shows the written report without the evidence report.';
182
+ }
183
+ return stepLogUploadsLine();
184
+ }
@@ -1,12 +1,16 @@
1
1
  import { recordingForCompletion, recordingCompletionBody } from '../upload/recording.js';
2
+ import { playClockFor } from '../run/playClock.js';
3
+ import { PHONE_VIEWPORT } from '../run/phone.js';
2
4
  import { randomUUID } from 'node:crypto';
3
5
  import { mkdir, readFile, stat } from 'node:fs/promises';
4
6
  import path from 'node:path';
5
7
  import { buildAggregate, writeAggregate } from '../run/aggregate.js';
8
+ import { capabilityNotesBody, thinRunLines, writeThinRunSection } from '../run/thinRun.js';
6
9
  import { reportPrOutcomes } from '../run/labsOutcome.js';
7
10
  import { finishJob } from '../run/settle.js';
8
11
  import { driverStartReason, failureReason } from '../run/failureReason.js';
9
- import { optionsFrom, unknownOptionNotes } from '../run/args.js';
12
+ import { optionsFrom, unknownOptionNotes, scopeProblems, isTierLength } from '../run/args.js';
13
+ import { briefWithFocus, focusLines, withStart } from '../run/focus.js';
10
14
  import { controllerPlan, displayName, quoteMatchesPlan, runsMatchPlan, wireId } from '../run/controllers.js';
11
15
  import { getDeps } from '../run/deps.js';
12
16
  import { createDriver } from '../run/drivers/index.js';
@@ -18,6 +22,7 @@ import { createHeartbeat } from '../run/heartbeat.js';
18
22
  import { createUsageLedger } from '../run/usage.js';
19
23
  import { configureSpendHold, createModelClient, ModelUnavailableError, ProxyError } from '../run/model.js';
20
24
  import { jobDir, runDir as runDirFor, JOB_FILES, RUN_FILES } from '../run/paths.js';
25
+ import { capabilityNoteLines } from '../run/readiness.js';
21
26
  import { readBridgeConfig } from "../run/drivers/stdio.js";
22
27
  import { WEBDRIVER_NAMES, readDriverConfig } from '../run/drivers/webdriver.js';
23
28
  import { BROWSER_FIX, automationChecks } from './check.js';
@@ -33,6 +38,7 @@ import { reconcileDroppedFindings } from '../run/dropped.js';
33
38
  import * as stateFile from '../run/state.js';
34
39
  import { emitRunEvents } from '../run/synthetic.js';
35
40
  import { serveBuildDir } from '../run/serveBuild.js';
41
+ import { stepLogSetting, stepLogUploadsLine } from '../config.js';
36
42
 
37
43
  /**
38
44
  * `ravensight-playtest run`: register a job, play it, upload it, finish it.
@@ -94,6 +100,52 @@ export async function runCommand(flags = {}, injected = {}) {
94
100
  * @param {(message: string) => void} log
95
101
  * @returns {Promise<number>}
96
102
  */
103
+ /**
104
+ * Whether a run uploads its step log (transcript.jsonl): the inputs it sent,
105
+ * what each observation read, the persona's notes and the checks made on its
106
+ * findings, with secrets from the local brief already scrubbed. It is what
107
+ * the evidence report in the dashboard is built from, so it uploads by
108
+ * default, for every project, including one set up before 0.10.0. A flag on
109
+ * the command line decides first: `--no-upload-step-log` keeps it on this
110
+ * machine, `--upload-step-log` (or the older `--upload-transcript`) sends it.
111
+ * Then `uploads.step_log` in the project config. The older
112
+ * `uploads.transcript` is not read (config.js stepLogSetting says why).
113
+ *
114
+ * @param {Object} options the run's parsed flags
115
+ * @param {Object|null} config the project config
116
+ * @returns {{upload: boolean, source: 'flag'|'step_log'|'default'}}
117
+ */
118
+ export function stepLogDecision(options = {}, config = null) {
119
+ if (options.noUploadStepLog === true) return { upload: false, source: 'flag' };
120
+ if (options.uploadTranscript === true) return { upload: true, source: 'flag' };
121
+ const setting = stepLogSetting(config);
122
+ if (setting.upload !== null) return { upload: setting.upload, source: setting.key };
123
+ return { upload: true, source: 'default' };
124
+ }
125
+
126
+ /** stepLogDecision's answer alone. */
127
+ export function stepLogUpload(options = {}, config = null) {
128
+ return stepLogDecision(options, config).upload;
129
+ }
130
+
131
+ /**
132
+ * The one line a run prints about its step log. When it uploads: what it
133
+ * holds, why, how long it is kept and how to keep it local. When it stays
134
+ * local: what kept it there, and what the dashboard shows without it (the
135
+ * server builds the evidence report from the step log and falls back to the
136
+ * written report).
137
+ *
138
+ * @param {{upload: boolean, source: string}} decision
139
+ * @returns {string}
140
+ */
141
+ export function stepLogLine(decision) {
142
+ if (decision.upload) return stepLogUploadsLine();
143
+ const setting = decision.source === 'flag'
144
+ ? '--no-upload-step-log'
145
+ : '"uploads": { "step_log": false } in .ravensight/config.json';
146
+ return `The step log (transcript.jsonl) stays on this machine (${setting}), so the dashboard shows the written report without the evidence report, which ties each finding to the moment it happened.`;
147
+ }
148
+
97
149
  async function run(flags, injected, deps, log) {
98
150
  const { options, unknown } = optionsFrom(flags);
99
151
  if (unknown.length > 0) {
@@ -106,6 +158,10 @@ async function run(flags, injected, deps, log) {
106
158
  const setup = await resolveSetup(deps, options, log);
107
159
  if (setup.code !== undefined) return setup.code;
108
160
  const { context, gameId, repoRoot, apiUrl, cliVersion, api } = setup;
161
+ // The step log uploads unless it is turned off; everything after this reads the one answer (the job journal keeps it for a resume).
162
+ const stepLog = stepLogDecision(options, context.config);
163
+ options.uploadTranscript = stepLog.upload;
164
+ log(stepLogLine(stepLog));
109
165
  const scopeRefusal = await tokenScopeRefusal(api);
110
166
  if (scopeRefusal !== null) {
111
167
  log(scopeRefusal.message);
@@ -122,7 +178,15 @@ async function run(flags, injected, deps, log) {
122
178
  if (controllers?.length > 1 && !['playwright_web', 'godot_driver'].includes(driverName)) { log('Comparisons currently require a web or Godot build. Nothing was charged.'); return EXIT.ENVIRONMENT; }
123
179
  const served = await serveBuildDirOption({ options, driverName, log, serve: injected.serveBuildDir });
124
180
  if (served === false) return EXIT.ENVIRONMENT;
125
- const target = resolveTarget(options, context.config, driverName, repoRoot);
181
+ // --tier, --minutes, --focus, --avoid and --start, checked before anything is priced.
182
+ const scope = scopeProblems(options, driverName);
183
+ if (scope.length > 0) {
184
+ for (const line of scope) log(line);
185
+ log('Nothing was registered or charged.');
186
+ return EXIT.ENVIRONMENT;
187
+ }
188
+ // --start opens a web build at a query or hash on its own address.
189
+ const target = withStart(resolveTarget(options, context.config, driverName, repoRoot), driverName === 'playwright_web' ? options.start : undefined);
126
190
  if (!target) {
127
191
  log('Point the run at a build: --build-url or --build-dir for a web build, --godot-project for Godot, or --driver-config for a native or text bridge.');
128
192
  return EXIT.ENVIRONMENT;
@@ -219,7 +283,8 @@ async function run(flags, injected, deps, log) {
219
283
  log(`${String(error && error.message)} The run goes ahead without expected_noise and test_account.`);
220
284
  }
221
285
 
222
- const runLength = options.runLength === 'long' ? 'long' : 'standard';
286
+ const tierRun = isTierLength(options.runLength);
287
+ const runLength = options.runLength === 'long' || tierRun ? options.runLength : 'standard';
223
288
  let estimate;
224
289
  try {
225
290
  estimate = await api.jobs.estimate(gameId, { modules, personas: personaSlugs, runLength, ...(controllers ? { controllers, driver: driverName } : {}) });
@@ -240,6 +305,12 @@ async function run(flags, injected, deps, log) {
240
305
  log('This server does not price long runs; nothing was registered or charged. Run without --long.');
241
306
  return EXIT.ENVIRONMENT;
242
307
  }
308
+ // A tier run is its own unit too: a server that does not price tiers would
309
+ // quote a standard run, and confirming that would buy the wrong length.
310
+ if (tierRun && !(Array.isArray(estimate.breakdown) && estimate.breakdown.some(line => line && /^playtest_tier_/.test(String(line.unit))))) {
311
+ log('This server does not price a run on a cloud tier; nothing was registered or charged. Run without --tier.');
312
+ return EXIT.ENVIRONMENT;
313
+ }
243
314
  if (runLength === 'long') {
244
315
  const factor = longRunFactor({ estimate, pack });
245
316
  options.longRunFactor = factor.factor;
@@ -251,7 +322,10 @@ async function run(flags, injected, deps, log) {
251
322
  log(bold(`This run: ${personaCount(personas.length)} (${personaSlugs.join(', ')}) on ${driverName}, ${formatCents(estimate.estimate_cents)} in total${units ? `: ${units}` : ''}.`));
252
323
  log(`Balance: ${formatCents(estimate.balance_cents)}.`);
253
324
  if (runLength === 'long') log(longRunLine(options.longRunFactor));
325
+ if (tierRun) log(`Each persona plays on the ${options.tier} tier's allowance${Number.isSafeInteger(options.minutes) ? ` for up to ${options.minutes} minutes` : ''}: its own model budget, action count and wall clock, set by the server.`);
326
+ for (const line of focusLines(options)) log(line);
254
327
  for (const line of actionBudgetLines({ options, personas, pack, localBrief })) log(line);
328
+ for (const line of videoPlanLines(options, driverName)) log(line);
255
329
  if (estimate.ok === false) {
256
330
  log(`That is more than the balance covers. Top up at ${estimate.topup_url || 'ravensight.io'} and run this again.`);
257
331
  // Nothing is wrong with the request; the account needs money. Spec 17's
@@ -291,7 +365,7 @@ async function run(flags, injected, deps, log) {
291
365
  build: { kind: driverName === 'playwright_web' ? 'url' : (WEBDRIVER_NAMES.includes(driverName) || driverName === 'cli_stdio') ? 'driver_config' : 'godot_project', ref: target },
292
366
  repo: { commit: (context.config && context.config.commit) || '', dirty: Boolean(context.config && context.config.dirty) },
293
367
  max_actions: Number.isInteger(options.maxActions) ? options.maxActions : null,
294
- ...(runLength === 'long' ? { run_length: 'long' } : {}),
368
+ ...(runLength !== 'standard' ? { run_length: runLength } : {}),
295
369
  pack_versions: { pack: pack.pack_version }
296
370
  }, { idempotencyKey });
297
371
  } catch (error) {
@@ -319,9 +393,11 @@ async function run(flags, injected, deps, log) {
319
393
  maxActions: options.maxActions ?? null,
320
394
  runLength,
321
395
  ...(runLength === 'long' ? { longRunFactor: options.longRunFactor } : {}),
396
+ // The focus is the run's own: a resume plays towards the same goals.
397
+ ...(options.focus?.length ? { focus: options.focus } : {}), ...(options.avoid?.length ? { avoid: options.avoid } : {}),
322
398
  controller: options.controller || 'standard',
323
399
  ...(controllers ? { controllers } : {}),
324
- recordVideo: Boolean(options.recordVideo || options.uploadVideo),
400
+ recordVideo: recordingMode(options, driverName),
325
401
  concurrency: options.concurrency ?? DEFAULT_CONCURRENCY,
326
402
  uploadVideo: Boolean(options.uploadVideo),
327
403
  uploadTranscript: Boolean(options.uploadTranscript)
@@ -671,9 +747,28 @@ export async function playJob({
671
747
  await stateFile.save(repoRoot, journal);
672
748
  settledState = finished.job ? finished.job.state : null;
673
749
  log(`job ${jobId} ${settledState || 'finished'}: refunded ${formatCents(finished.refunded_cents)}.`);
750
+ // Each thin run, with what it was charged now the job has settled.
751
+ for (const thin of Array.isArray(finished.thin_runs) ? finished.thin_runs : []) {
752
+ const lines = thinRunLines(thin);
753
+ if (lines.length > 0) log(`run ${thin.run_id}${thin.persona ? ` (${thin.persona})` : ''}: ${lines.join(' ')}`);
754
+ }
674
755
  }
675
756
  }
676
757
  log(`Reports: ${directory}`);
758
+ // What the personas could not cover, with what to add: the next run is only
759
+ // fuller if the developer acts on it, so it is said here and not only in a file.
760
+ const written = [];
761
+ for (const result of results) {
762
+ if (!result || !result.runId) continue;
763
+ const markdown = await readFile(path.join(runDirFor(repoRoot, jobId, result.runId), RUN_FILES.reportMd), 'utf8').catch(() => null);
764
+ if (markdown) written.push({ persona: result.persona, markdown });
765
+ }
766
+ for (const line of capabilityNoteLines(written)) log(line);
767
+ // Where each run's video is, or why there is none.
768
+ for (const result of results) {
769
+ if (!result || !result.runId) continue;
770
+ log(await videoSummaryLine({ directory: runDirFor(repoRoot, jobId, result.runId), persona: result.persona, options, driverName }));
771
+ }
677
772
 
678
773
  if (canceled) return EXIT.CANCELED;
679
774
  if (reportBudgetRefused || reportRefused) return EXIT.FAILED;
@@ -726,7 +821,7 @@ export async function playPersonaRun({
726
821
  const runTarget = entry.target || target;
727
822
  let driver;
728
823
  try {
729
- driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime }));
824
+ driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone }));
730
825
  } catch (error) {
731
826
  // A driver that cannot even be built (the browser package missing, say) is
732
827
  // what a new machine hits first. The run is completed as failed now, with
@@ -796,14 +891,22 @@ export async function playPersonaRun({
796
891
  // The brief this command fetched and checked is complete, not the
797
892
  // pack's copy, which a pack bundle does not always carry.
798
893
  // A feature scenario brings its own, built from the frozen specification.
799
- brief: entry.brief || brief || pack.brief || null,
894
+ // --focus and --avoid ride in a copy of the brief the persona reads; the brief itself is unchanged.
895
+ brief: briefWithFocus(entry.brief || brief || pack.brief || null, options),
800
896
  localBrief: usableLocalBrief(localBrief),
801
897
  intentNotes: pack.intent_notes || [],
802
898
  schemas: pack.schemas || [],
803
899
  maxActions,
804
900
  heartbeat,
805
901
  ledger,
806
- recordVideo: Boolean(options.recordVideo || options.uploadVideo),
902
+ recordVideo: recordingMode(options, driverName),
903
+ edgePass: options.noEdgePass !== true,
904
+ replayFindings: options.noReplay !== true,
905
+ // A web run's findings are replayed in a second browser of the same kind, on the same target, with no recording.
906
+ ...(driverName === 'playwright_web' ? { replayDriver: () => makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone })) } : {}),
907
+ // A run sold by the minute stops on the clock (../run/playClock.js).
908
+ playClock: playClockFor(options, entry),
909
+ ...(options.phone === true && driverName === 'playwright_web' ? { viewport: PHONE_VIEWPORT } : {}),
807
910
  // Written the moment the warning arrives, not after the run: a run that
808
911
  // then fails still says in state.json that it was warned.
809
912
  onBudgetWarning: async () => {
@@ -1013,6 +1116,11 @@ export async function deliver({ deps, api, gameId, jobId, runId, directory, outc
1013
1116
  // The run card's duration. The server lane accepts `duration`; an older
1014
1117
  // server ignores a key it does not know.
1015
1118
  if (outcome.duration) body.duration = durationBody(outcome.duration);
1119
+ // What the playtester could not read or press, when the run met a limit. The
1120
+ // server only shows these back in a thin run's explanation; an older server
1121
+ // ignores a key it does not know.
1122
+ const capabilityNotes = capabilityNotesBody(outcome);
1123
+ if (capabilityNotes.length > 0) body.capability_notes = capabilityNotes;
1016
1124
  // Keep the same bounded opt-in status in the older-server partial-report fallback.
1017
1125
  const recording = options.uploadVideo === true ? recordingForCompletion(outcome.recording) : null;
1018
1126
  Object.assign(body, await recordingCompletionBody(directory, recording ? { recording } : {}, options.uploadVideo === true));
@@ -1073,6 +1181,13 @@ export async function deliver({ deps, api, gameId, jobId, runId, directory, outc
1073
1181
  if (answer && Array.isArray(answer.report_lint) && answer.report_lint.length > 0) {
1074
1182
  log(`run ${runId}: report lint: ${answer.report_lint.join('; ')}`);
1075
1183
  }
1184
+ // A thin run: the server says why it was short, what to try next and how
1185
+ // it is billed. Said here and written into report.md, in its words.
1186
+ const thin = thinRunLines(answer && answer.run && answer.run.thin_run);
1187
+ if (thin.length > 0) {
1188
+ log(`run ${runId}: ${thin.join(' ')}`);
1189
+ await writeThinRunSection(directory, answer.run.thin_run);
1190
+ }
1076
1191
  return answer;
1077
1192
  } catch (error) {
1078
1193
  if (delivery) {
@@ -1222,8 +1337,8 @@ async function aggregatePhase({
1222
1337
 
1223
1338
  // The aggregate reads reports off disk, so a resumed job whose earlier runs
1224
1339
  // were played by a previous process is covered too.
1225
- // A failed run's report explains the failure and its unit is refunded. It is
1226
- // not a result to summarise, and the server refuses a summary of only those.
1340
+ // A failed run's report explains the failure; what it is charged is the
1341
+ // server's decision. It is not a result to summarise, and the server refuses a summary of only those.
1227
1342
  const reports = (await loadRunReports(repoRoot, jobId, personaRuns, journal))
1228
1343
  .map(run => (run.state === 'failed' ? { ...run, report: null } : run));
1229
1344
  let aggregate;
@@ -1518,7 +1633,7 @@ export async function resolveSetup(deps, options, log) {
1518
1633
  *
1519
1634
  * @returns {Object}
1520
1635
  */
1521
- export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime }) {
1636
+ export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false }) {
1522
1637
  // Only the browser driver sends key chords with a modifier.
1523
1638
  const modifier = driverName === 'playwright_web' ? resolveKeyModifier(keyModifier).modifier : null;
1524
1639
  const godot = driverName === 'godot_driver'
@@ -1529,6 +1644,11 @@ export function driverOptions({ headless, driverName, target, directory, entry,
1529
1644
  return {
1530
1645
  headless,
1531
1646
  ...(modifier ? { modifier } : {}),
1647
+ // A canvas game in the browser is parked between actions too, unless the
1648
+ // game has to run in real time.
1649
+ ...(driverName === 'playwright_web' && realtime === true ? { freezeTime: false } : {}),
1650
+ // A phone sized screen played with touch (--phone).
1651
+ ...(driverName === 'playwright_web' && phone === true ? { touch: true } : {}),
1532
1652
  ...godot,
1533
1653
  playtest: {
1534
1654
  token: entry.playtest_token || null,
@@ -1702,6 +1822,76 @@ export function actionBudgetLines({ options = {}, personas = [], pack = {}, loca
1702
1822
  return lines;
1703
1823
  }
1704
1824
 
1825
+ /** Said before the price is confirmed when a run would leave no video behind. */
1826
+ export const NO_VIDEO_LINE = 'No video will be recorded (--no-record-video). Leave the flag out to keep one on this machine.';
1827
+
1828
+ /** Drivers that can record what they play. */
1829
+ const RECORDING_DRIVERS = Object.freeze(['playwright_web', 'godot_driver']);
1830
+
1831
+ /**
1832
+ * How a run records: `true` when a video was asked for (it is held to the
1833
+ * upload limits), `'auto'` for the default (kept on this machine, never a
1834
+ * reason to end or change a run), `false` when turned off or when the driver
1835
+ * cannot record.
1836
+ *
1837
+ * @param {Object} options
1838
+ * @param {string} driverName
1839
+ * @returns {boolean|'auto'}
1840
+ */
1841
+ export function recordingMode(options = {}, driverName = '') {
1842
+ if (options.recordVideo === true || options.uploadVideo === true) return true;
1843
+ // A resumed job keeps what its journal says.
1844
+ if (options.recordVideo === 'auto') return RECORDING_DRIVERS.includes(driverName) ? 'auto' : false;
1845
+ if (options.noRecordVideo === true || options.recordVideo === false) return false;
1846
+ return RECORDING_DRIVERS.includes(driverName) ? 'auto' : false;
1847
+ }
1848
+
1849
+ /**
1850
+ * What a run will do about video, said before the price is confirmed.
1851
+ *
1852
+ * @param {Object} options
1853
+ * @param {string} driverName
1854
+ * @returns {Array<string>}
1855
+ */
1856
+ export function videoPlanLines(options = {}, driverName = '') {
1857
+ if (driverName === 'cli_stdio') return [];
1858
+ const mode = recordingMode(options, driverName);
1859
+ if (mode === false) return [RECORDING_DRIVERS.includes(driverName) ? NO_VIDEO_LINE : `No video will be recorded: ${driverName} cannot record what it plays.`];
1860
+ if (options.uploadVideo === true) return ['A video of each run is recorded and uploaded with the reports (--upload-video).'];
1861
+ if (mode === true) return ['A video of each run is kept on this machine, in its run folder. It is not uploaded.'];
1862
+ return [`A video of each run is kept on this machine, in its run folder${driverName === 'godot_driver' ? ' (Godot needs ffmpeg for it)' : ''}. It is not uploaded; --upload-video sends it, --no-record-video turns it off.`];
1863
+ }
1864
+
1865
+ /**
1866
+ * One line of the run summary: where a run's video is, or why there is none.
1867
+ *
1868
+ * @param {Object} args
1869
+ * @param {string} args.directory the run's folder
1870
+ * @param {string} [args.persona]
1871
+ * @param {Object} [args.options]
1872
+ * @param {string} [args.driverName]
1873
+ * @returns {Promise<string>}
1874
+ */
1875
+ export async function videoSummaryLine({ directory, persona = '', options = {}, driverName = '' }) {
1876
+ const who = persona ? ` (${persona})` : '';
1877
+ for (const name of ['session.webm', 'session.mp4']) {
1878
+ const file = path.join(directory, name);
1879
+ const info = await stat(file).catch(() => null);
1880
+ if (info && info.isFile()) {
1881
+ const meta = await readFile(path.join(directory, 'recording.json'), 'utf8').then(JSON.parse).catch(() => null);
1882
+ const seconds = meta && Number.isFinite(meta.durationMs) ? `, ${Math.round(meta.durationMs / 1000)} s` : '';
1883
+ const partial = meta && meta.status === 'partial' ? `, partial: ${meta.reason || 'it stopped early'}` : '';
1884
+ return `Video${who}: ${file} (${(info.size / (1024 * 1024)).toFixed(1)} MB${seconds}${partial})${options.uploadVideo === true ? '' : '. Kept on this machine, not uploaded.'}`;
1885
+ }
1886
+ }
1887
+ if (recordingMode(options, driverName) === false) {
1888
+ return `No video${who}: ${RECORDING_DRIVERS.includes(driverName) ? 'turned off with --no-record-video' : `${driverName || 'this driver'} cannot record what it plays`}.`;
1889
+ }
1890
+ const meta = await readFile(path.join(directory, 'recording.json'), 'utf8').then(JSON.parse).catch(() => null);
1891
+ const why = meta ? (meta.detail || meta.failure || meta.reason || 'the recording did not finish') : 'the run ended before a recording was made';
1892
+ return `No video${who}: ${String(why).replace(/_/g, ' ')}.`;
1893
+ }
1894
+
1705
1895
  /** How long the health check waits for an answer. */
1706
1896
  export const HEALTH_TIMEOUT_MS = 10000;
1707
1897
 
@@ -1818,12 +2008,17 @@ export const DEFAULT_MAX_ACTIONS = 25;
1818
2008
  * @returns {number}
1819
2009
  */
1820
2010
  export function resolveMaxActions(options, persona, pack, run = null) {
1821
- const factor = options && options.runLength === 'long'
1822
- ? (Number.isInteger(options.longRunFactor) && options.longRunFactor >= 1 ? options.longRunFactor : longRunFactor({ run, pack }).factor)
1823
- : 1;
1824
2011
  const fromServer = Number(run && ((run.limits && run.limits.max_actions) ?? run.max_actions)) || null;
1825
2012
  const routing = Number(pack && pack.routing && pack.routing.max_actions) || null;
2013
+ // A run on a cloud tier is sold a longer play than a standard run: the persona's
2014
+ // patience grows by the same share as the run's own action limit did.
2015
+ const tierFactor = options && isTierLength(options.runLength) && fromServer && routing ? Math.max(1, Math.round(fromServer / routing)) : null;
2016
+ const factor = tierFactor || (options && options.runLength === 'long'
2017
+ ? (Number.isInteger(options.longRunFactor) && options.longRunFactor >= 1 ? options.longRunFactor : longRunFactor({ run, pack }).factor)
2018
+ : 1);
1826
2019
  const patience = Number(persona && persona.patience_actions) || null;
2020
+ // A tier run is sold by the minute and stops on its play clock
2021
+ // (../run/playClock.js), so no action count is guessed from the wall clock here.
1827
2022
  const candidates = [
1828
2023
  Number.isInteger(options && options.maxActions) ? options.maxActions : null,
1829
2024
  patience === null ? null : patience * factor,
@@ -1,6 +1,6 @@
1
1
  import { readdir } from 'node:fs/promises';
2
2
  import { createContext } from '../api/index.js';
3
- import { resolveGameId } from '../config.js';
3
+ import { resolveGameId, stepLogSetting } from '../config.js';
4
4
  import { withAuthHandling } from '../auth/session.js';
5
5
  import { paths } from '../paths.js';
6
6
  import { readState } from '../state/index.js';
@@ -68,8 +68,12 @@ async function drainJob(context, jobId, flags) {
68
68
 
69
69
  const uploadsConfig = (context.config && context.config.uploads) || {};
70
70
  const includeVideo = flags.video === undefined ? Boolean(uploadsConfig.video) : Boolean(flags.video);
71
+ // With no flag, a job sends what it was run with: a persona run's step log uploads by default
72
+ // (run.js stepLogDecision) and the job journal remembers that. A job with no such record makes the
73
+ // same decision: it sends the step log unless uploads.step_log is false.
74
+ const journaled = state && state.options && typeof state.options.uploadTranscript === 'boolean' ? state.options.uploadTranscript : null;
71
75
  const includeTranscript = flags.transcript === undefined
72
- ? Boolean(uploadsConfig.transcript)
76
+ ? (journaled ?? stepLogSetting(context.config).upload !== false)
73
77
  : Boolean(flags.transcript);
74
78
 
75
79
  const runIds = await localRunIds(jobId, { repoRoot });
@@ -231,7 +231,7 @@ export async function validateCommand(head, flags = {}, injected = {}) {
231
231
  }
232
232
  log(`This validation: ${size} runs on ${baseRef} and ${size} on ${headRef}, ${formatCents(estimate.estimate_cents)} in total. Balance: ${formatCents(estimate.balance_cents)}.`);
233
233
  if (size < MIN_RUNS_FOR_A_VERDICT) log(`With fewer than ${MIN_RUNS_FOR_A_VERDICT} runs a side the result is a direction, never a verdict. --runs ${MIN_RUNS_FOR_A_VERDICT} costs ${formatCents((estimate.estimate_cents / size) * MIN_RUNS_FOR_A_VERDICT)}.`);
234
- log('A run that does not earn its unit is refunded and does not count. If one side ends with no usable run there is nothing to compare, and the runs on the other side that played and reported keep their units: those runs happened and their reports are real.');
234
+ log('A run that does not earn its unit does not count, and the server bills it at no more than what it cost us, or refunds it in full when the cause was ours. If one side ends with no usable run there is nothing to compare, and the runs on the other side that played and reported keep their units: those runs happened and their reports are real.');
235
235
  const floorLine = startBalanceLine(estimate);
236
236
  if (floorLine) log(floorLine);
237
237
  if (estimate.ok === false && floorLine) {
@@ -11,6 +11,7 @@ import { detectGodotBinary, majorMinor } from '../godot.js';
11
11
  import { buildPack, HOSTED_GODOT, PACK_NAME } from '../simulation/godotPack.js';
12
12
  import { defaultBase } from './validate.js';
13
13
  import { DIMENSION_3D, dimensionGate } from '../run/dimension.js';
14
+ import { queueInfo, queueLine } from '../hosted/status.js';
14
15
 
15
16
  /**
16
17
  * `ravensight-playtest validate <branch> --hosted`: two uploaded Godot builds, the
@@ -27,6 +28,11 @@ export const DEFAULT_STEPS = 300;
27
28
  export const MAX_STEPS = 10000;
28
29
  const POLL_MS = 15000;
29
30
  const WAIT_MS = 80 * 60 * 1000;
31
+ // The longest this command waits in all, line included. The server's own line ends
32
+ // sooner (six hours, and 45 minutes more for the second machine), so this is a ceiling.
33
+ export const QUEUE_WAIT_MS = 8 * 60 * 60 * 1000;
34
+ // Reads that failed in a row before the command stops waiting.
35
+ export const MAX_POLL_FAILURES = 20;
30
36
  const money = cents => `$${(cents / 100).toFixed(2)}`;
31
37
  const BUILD_POLL_MS = 5000;
32
38
  const BUILD_WAIT_MS = 15 * 60 * 1000;
@@ -66,6 +72,16 @@ export function comparisonLines(pair) {
66
72
  return lines;
67
73
  }
68
74
 
75
+ /**
76
+ * "Queued, position 2, expected to start in about 14 minutes." for an open comparison
77
+ * the server says is waiting for a machine (`queued` and `queue`, the fields a cloud
78
+ * playtest carries), or null. A cancel or a review is said elsewhere.
79
+ */
80
+ export function queuedLine(pair, now = Date.now()) {
81
+ if (!pair || pair.state !== 'open' || pair.cancelRequested || pair.underReview || pair.queued !== true) return null;
82
+ return queueLine(queueInfo(pair), now);
83
+ }
84
+
69
85
  /** A ready build of these exact bytes is reused, so a retry pays no second deposit. */
70
86
  async function ensureBuild({ api, gameId, built, sleep, fetchImpl, log, label, clock, created: createdIds }) {
71
87
  const manifest = { sha256: built.sha256, bytes: built.bytes, entrypoint: PACK_NAME, args: [] };
@@ -264,7 +280,10 @@ export async function validateHostedCommand(head, flags = {}, injected = {}) {
264
280
  await release();
265
281
  return EXIT.ENVIRONMENT;
266
282
  }
267
- log(`Comparison ${pair.pairId} started.`);
283
+ // A paid comparison is never refused for a busy service: it waits in line for a
284
+ // cloud machine, and says its place and estimated start as a cloud playtest does.
285
+ let said = queuedLine(pair, clock());
286
+ log(said ? `Comparison ${pair.pairId} is paid for and waiting for a cloud machine. ${said}` : `Comparison ${pair.pairId} started.`);
268
287
  const link = jobLink(gameId, pair.base.jobId, setup.apiUrl);
269
288
  if (link) log(`Follow it at ${link}`);
270
289
  if (flags.wait === false) {
@@ -272,10 +291,33 @@ export async function validateHostedCommand(head, flags = {}, injected = {}) {
272
291
  return EXIT.OK;
273
292
  }
274
293
 
275
- const deadline = clock() + WAIT_MS;
276
- while (pair.state !== 'settled' && !pair.underReview && clock() < deadline) {
294
+ // Two clocks, both this command's own. `ceiling` is absolute and set once: nothing
295
+ // the server answers can move it. `deadline` is the run's wait; it restarts once,
296
+ // when the comparison leaves the line, and never past the ceiling.
297
+ const ceiling = clock() + QUEUE_WAIT_MS;
298
+ let deadline = Math.min(ceiling, clock() + WAIT_MS);
299
+ let failures = 0;
300
+ while (pair.state !== 'settled' && !pair.underReview) {
301
+ const at = clock();
302
+ if (at >= ceiling || (!said && at >= deadline)) break;
277
303
  await sleep(POLL_MS);
278
- try { pair = await api.hosted.readPair(gameId, pair.pairId); } catch (error) { if (error.status === 404) throw error; }
304
+ let fresh;
305
+ try { fresh = await api.hosted.readPair(gameId, pair.pairId); } catch (error) {
306
+ if (error.status === 404) throw error;
307
+ // A read that failed says nothing new: it extends no wait, and too many in a row end it.
308
+ failures += 1;
309
+ if (failures >= MAX_POLL_FAILURES) break;
310
+ continue;
311
+ }
312
+ failures = 0;
313
+ pair = fresh;
314
+ const line = queuedLine(pair, clock());
315
+ if (line && line !== said) log(line);
316
+ if (!line && said) {
317
+ deadline = Math.min(ceiling, clock() + WAIT_MS);
318
+ if (pair.state !== 'settled') log('A cloud machine is free: this comparison is running.');
319
+ }
320
+ said = line;
279
321
  }
280
322
  if (flags.json) console.log(JSON.stringify(pair));
281
323
  if (pair.state !== 'settled' && pair.underReview) {
@@ -283,7 +325,10 @@ export async function validateHostedCommand(head, flags = {}, injected = {}) {
283
325
  return EXIT.OK;
284
326
  }
285
327
  if (pair.state !== 'settled') {
286
- log(`Comparison ${pair.pairId} is still running. The job page shows it when it finishes.`);
328
+ // Giving up waiting changes nothing on the server: no cancel and no refund.
329
+ const where = link ? `Check it at ${link}` : 'The job page shows it when it finishes';
330
+ log(said ? `Comparison ${pair.pairId} (job ${pair.base.jobId}) is still waiting for a cloud machine. It is paid for and keeps its place. ${where}.`
331
+ : `Comparison ${pair.pairId} (job ${pair.base.jobId}) is still running. ${where}.`);
287
332
  return EXIT.OK;
288
333
  }
289
334
  for (const line of comparisonLines(pair)) log(line);