ravensight-playtest 0.13.3 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +82 -1
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +4 -4
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +19 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/run.js +40 -5
  10. package/src/commands/setup.js +176 -0
  11. package/src/packs/index.js +37 -5
  12. package/src/packs/keys.json +11 -0
  13. package/src/packs/pack-signing-hashes.json +7 -0
  14. package/src/packs/pack-signing-vectors.json +119 -0
  15. package/src/packs/signature.js +186 -0
  16. package/src/run/anygame/gamenotes.js +74 -12
  17. package/src/run/anygame/index.js +97 -34
  18. package/src/run/anygame/language.js +100 -10
  19. package/src/run/anygame/memory.js +70 -13
  20. package/src/run/anygame/shared-hashes.json +9 -8
  21. package/src/run/anygame/shared.js +6 -5
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +5 -0
  24. package/src/run/claimwords.js +43 -7
  25. package/src/run/drivers/godot-cursor.js +96 -0
  26. package/src/run/drivers/godot-observation.js +29 -5
  27. package/src/run/drivers/godot.js +60 -5
  28. package/src/run/drivers/web.js +181 -10
  29. package/src/run/egress.js +282 -0
  30. package/src/run/eventclaims.js +102 -6
  31. package/src/run/events.js +64 -6
  32. package/src/run/gameMemory.js +14 -5
  33. package/src/run/honesty.js +49 -2
  34. package/src/run/judge.js +22 -10
  35. package/src/run/liveFeed.js +254 -0
  36. package/src/run/networkRun.js +54 -0
  37. package/src/run/personaLoop.js +70 -20
  38. package/src/run/pixels.js +491 -2
  39. package/src/run/replay.js +11 -0
  40. package/src/run/resume.js +3 -1
  41. package/src/run/tools.js +2 -2
@@ -232,8 +232,25 @@ are held, so the persona's tools are made of them:
232
232
  A named end (`from: "Army"`) is resolved against the last outline like a click
233
233
  target and sent as the centre the outline prints. In lockstep every event is a
234
234
  `step` event of type `mouse`, so a trace replays a drag move for move. There is
235
- no `select`: a dropdown is opened and picked with clicks, a slider is dragged,
236
- and the refusal is recorded as a limit of the runner.
235
+ no `select` before addon 1.5.0: a dropdown is opened and picked with clicks, a
236
+ slider is dragged, and the refusal is recorded as a limit of the runner.
237
+
238
+ In lockstep the desktop's mouse never reaches a node (addon 1.6.0), and from
239
+ 1.7.0 the driver also undoes what a desktop mouse event did to the engine's
240
+ own pointer state before the guard stopped it: before every physics tick and
241
+ every frame it sends the run's pointer back through Input, so
242
+ `Input.is_mouse_button_pressed`, `Input.get_mouse_button_mask` and
243
+ `Input.get_last_mouse_velocity` (the desktop's motion is sent back reversed,
244
+ so it cancels) read the run's pointer. The real pointer is never moved. What
245
+ this cannot reach: a viewport's `get_mouse_position` and a node's
246
+ `get_global_mouse_position` or `get_local_mouse_position` in the game's own
247
+ window read the desktop's pointer inside the engine, and an addon can only
248
+ change that by moving it. So the CLI lists where a game calls them (up to ten
249
+ places, from its `.gd` and `.cs` files) in the trace header as `cursor_reads`,
250
+ and a replay repeats them with a note. Every step answer and `ping` carry
251
+ `desktop_pointer`, how many desktop mouse events got in; the run's metrics
252
+ call it `desktop_pointer_events`. The mouse speed Godot reports is measured on
253
+ the wall clock, so it is never exact in lockstep even with no desktop input.
237
254
 
238
255
  ## Dropdowns, sliders and tabs
239
256
 
@@ -249,6 +266,53 @@ the ones it has. The outline prints what is chosen and offered
249
266
  (`value=50 (from 0 to 100)`). The persona's `select` tool is offered on
250
267
  `godot_driver` when the project's addon is 1.5.0 or newer.
251
268
 
269
+ ### Menus, separators and locked options (addon 1.6.0)
270
+
271
+ A dropdown's list, a `MenuButton`'s menu and a `PopupMenu` the game pops up
272
+ (a right click menu) are windows the engine owns, so until 1.6.0 the outline
273
+ never showed one open and a click on an option's text found nothing. Now:
274
+
275
+ - An open menu is in the outline with its items, its place and `[open menu]`,
276
+ under the control that opened it (`PopupMenu menu options=[Easy | Normal (checked) | Hard] 200x90 centre(120,465) [open menu]`),
277
+ with a note on how to choose. A plain click on an option's text, when one
278
+ open menu has it, chooses it: `Chose "Hard" in the open menu.` In lockstep it
279
+ is a `select` step event of that menu, so a replay makes the same choice.
280
+ - `select` takes a `MenuButton` (it opens the menu and picks, a player's two
281
+ clicks) and an open `PopupMenu`. The engine's signals are sent as a click on
282
+ the item sends them (`id_pressed`, then `index_pressed`), and the menu closes
283
+ unless the game keeps it open. A closed menu is refused: a player opens it
284
+ first.
285
+ - A further menu (addon 1.7.0). An item that opens one is shown as `(submenu)`.
286
+ A click on its text, or a `select` naming it, opens the further menu beside
287
+ it, as a player's hover does (`Opened "Export": its items are in the
288
+ outline, under it.`), and the outline then lists it under its parent. A
289
+ `select` can also take the whole path in one go, `option: "Export > PNG"`
290
+ on the menu button or the open menu: every item but the last has to open a
291
+ further menu, the whole path is checked before anything opens, and a part
292
+ that is not there is refused with what that menu offers. Choosing an item
293
+ closes its menu and the menus that opened it, as the engine does. In
294
+ lockstep the path is one `select` step event, so a replay makes the same
295
+ choice. The further menu is placed at its parent's right edge, level with
296
+ the item by an even share of the parent's height (the engine does not expose
297
+ an item's row); the outline reports where it really is.
298
+ - A separator is not an option, a hidden tab is not offered, and a disabled
299
+ option, item or tab is shown as `(disabled)` and refused, as a player cannot
300
+ pick it. A ticked menu item shows `(checked)`. An `ItemList` that takes
301
+ several picks hears a pick as `multi_selected`. Choosing the option already
302
+ in effect sends nothing, unless the control allows a reselect, and says
303
+ `"Iron" was already chosen.` A dropdown chosen by `select` while its list is
304
+ open closes the list.
305
+ - A `TabBar` is in the outline with its tabs (it was dropped, having no text of
306
+ its own).
307
+ - A dialog (`AcceptDialog`, `ConfirmationDialog`) shows its title, its message
308
+ and its buttons, and a click on a button lands on it: a control inside a
309
+ dialog or popup window is placed in the game window's pixels. A closed dialog
310
+ or menu is not in the outline.
311
+ - A menu or dialog the game draws in a window of its own (with
312
+ `display/window/subwindows/embed_subwindows` off) is marked
313
+ `[open menu own window, not in the screenshot]`: the picture of the game's
314
+ window does not show it, and a click on a control inside it is not placed.
315
+
252
316
  ## The frame strip
253
317
 
254
318
  While a held key, a held press or a timed sequence plays, the addon takes up
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.13.3",
3
+ "version": "0.17.0",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/playtest/",
@@ -49,9 +49,9 @@
49
49
  "./api": "./src/api/index.js"
50
50
  },
51
51
  "scripts": {
52
- "test": "node --test --test-reporter=spec 'src/**/!(godot-real|godot-draw.real|godot-inputs.real|godot-replay.real|godot-tester.real|web.e2e|web.containment.e2e|web.inputs.e2e|web.honesty.e2e|web.followups.e2e|web.replay.e2e|web.anygame.e2e|web.events.e2e|web.tester.e2e|web.livesite.e2e|web.urlrun.e2e|scaffold.godot|template3d.godot).test.js'",
53
- "test:godot": "node scripts/gated-test.mjs RAVENSIGHT_RECORDING_E2E some -- --test --test-concurrency=1 --test-reporter=spec src/run/drivers/godot-real.test.js src/run/drivers/godot-draw.real.test.js src/run/drivers/godot-inputs.real.test.js src/run/drivers/godot-replay.real.test.js src/run/drivers/godot-tester.real.test.js src/create/scaffold.godot.test.js src/create/template3d.godot.test.js",
54
- "test:e2e": "node scripts/gated-test.mjs RAVENSIGHT_E2E all -- --test --test-reporter=spec src/run/drivers/web.e2e.test.js src/run/drivers/web.containment.e2e.test.js src/run/drivers/web.inputs.e2e.test.js src/run/drivers/web.honesty.e2e.test.js src/run/drivers/web.followups.e2e.test.js src/run/drivers/web.tester.e2e.test.js src/run/drivers/web.replay.e2e.test.js src/run/drivers/web.anygame.e2e.test.js src/run/drivers/web.events.e2e.test.js src/run/drivers/web.livesite.e2e.test.js src/commands/run.urlrun.e2e.test.js",
52
+ "test": "node --test --test-reporter=spec 'src/**/!(godot-real|godot-draw.real|godot-inputs.real|godot-menus.real|godot-replay.real|godot-tester.real|web.e2e|web.containment.e2e|web.inputs.e2e|web.honesty.e2e|web.followups.e2e|web.replay.e2e|web.anygame.e2e|web.languages.e2e|web.events.e2e|web.tester.e2e|web.livesite.e2e|web.network.e2e|web.moving.e2e|web.urlrun.e2e|scaffold.godot|template3d.godot).test.js'",
53
+ "test:godot": "node scripts/gated-test.mjs RAVENSIGHT_RECORDING_E2E some -- --test --test-concurrency=1 --test-reporter=spec src/run/drivers/godot-real.test.js src/run/drivers/godot-draw.real.test.js src/run/drivers/godot-inputs.real.test.js src/run/drivers/godot-menus.real.test.js src/run/drivers/godot-replay.real.test.js src/run/drivers/godot-tester.real.test.js src/create/scaffold.godot.test.js src/create/template3d.godot.test.js",
54
+ "test:e2e": "node scripts/gated-test.mjs RAVENSIGHT_E2E all -- --test --test-reporter=spec src/run/drivers/web.e2e.test.js src/run/drivers/web.containment.e2e.test.js src/run/drivers/web.inputs.e2e.test.js src/run/drivers/web.honesty.e2e.test.js src/run/drivers/web.followups.e2e.test.js src/run/drivers/web.tester.e2e.test.js src/run/drivers/web.replay.e2e.test.js src/run/drivers/web.anygame.e2e.test.js src/run/drivers/web.languages.e2e.test.js src/run/drivers/web.events.e2e.test.js src/run/drivers/web.livesite.e2e.test.js src/run/drivers/web.network.e2e.test.js src/run/drivers/web.moving.e2e.test.js src/commands/run.urlrun.e2e.test.js",
55
55
  "lint": "node scripts/no-dashes.mjs",
56
56
  "audit:honesty": "node --test --test-reporter=spec src/run/honestyCorpus.test.js",
57
57
  "test:android": "node scripts/gated-test.mjs RAVENSIGHT_ANDROID_E2E all -- --test --test-timeout=240000 --test-concurrency=1 src/run/drivers/mobile/native-real.test.js",
package/src/api/README.md CHANGED
@@ -185,6 +185,7 @@ Refusals worth handling by code:
185
185
  | `api.runs.heartbeat(gameId, jobId, runId, opts)` | `PATCH /jobs/:jobId/runs/:runId` with no state |
186
186
  | `api.runs.transition(gameId, jobId, runId, state, opts)` | the same PATCH, with a state |
187
187
  | `api.runs.uploads(gameId, jobId, runId, { files, includeVideo })` | `POST .../uploads` |
188
+ | `api.runs.live(gameId, jobId, runId, body)` | `POST .../live`: recent steps and an optional small JPEG frame for the job's live view; never retried, 8 s limit, free |
188
189
  | `api.runs.complete(gameId, jobId, runId, body)` | `POST .../complete` |
189
190
 
190
191
  `opts` for both heartbeat and transition is
@@ -278,13 +279,19 @@ const { bundle, etag, fromCache, fetchedAt, stale } = await packs.get({
278
279
  - `fetchedAt` is an ISO string. `stale` is true whenever the answer did not
279
280
  come from this process's own successful request.
280
281
 
282
+ - Every bundle, fresh or cached, must carry a signature that verifies
283
+ against a key in `src/packs/keys.json` (or `RAVENSIGHT_PACK_TRUSTED_KEYS`
284
+ for a local server) for exactly this game, job and module list; otherwise
285
+ `PackSignatureError` (a `CliError` with a hint). That error is never treated
286
+ as offline, so it never falls back to the cache. See `src/packs/signature.js`.
287
+
281
288
  `packs.cached({ apiUrl, gameId, modules })` reads the cache without any
282
289
  network. `packs.sync({ api, gameId, modules })` forces a fetch and returns
283
290
  the same shape.
284
291
 
285
292
  The bundle's own fields are the server's: `pack_version`, `generated_at`,
286
293
  `personas`, `skills`, `schemas`, `routing`, `code_brief`, `engine`,
287
- `intent_notes`, `etag`.
294
+ `intent_notes`, `etag`, and `signature`.
288
295
 
289
296
  ## uploadRunDir and finalizeRun
290
297
 
package/src/api/client.js CHANGED
@@ -96,7 +96,10 @@ export function createClient(options = {}) {
96
96
  idempotent: Boolean(opts.idempotent),
97
97
  raw: Boolean(opts.raw),
98
98
  onResponseRaw: opts.onResponseRaw,
99
- ...transport
99
+ ...transport,
100
+ // A best effort call (the live view) sets its own: no retry, a short time limit.
101
+ ...(opts.retries !== undefined ? { retries: opts.retries } : {}),
102
+ ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {})
100
103
  });
101
104
  }
102
105
 
@@ -210,6 +213,16 @@ export function createClient(options = {}) {
210
213
  body: { modules, personas, ...(controllers ? { controllers, driver } : {}), ...(typeof runLength === 'string' && runLength !== 'standard' ? { run_length: runLength } : {}), ...(simulation ? { simulation } : {}), ...(validate ? { validate } : {}), ...(feature ? { feature } : {}), ...(acceptance ? { acceptance: true } : {}) }
211
214
  }).then(answer => answer.body),
212
215
 
216
+ /**
217
+ * A proposed playtest for a goal: personas, the brief's state, each place it
218
+ * can run with its price and the commands that start it. Free; it starts,
219
+ * holds and charges nothing.
220
+ */
221
+ plan: (gameId, { goal, where, personas, tier, minutes, runLength } = {}) =>
222
+ request('POST', `${gameBase(gameId)}/plan`, {
223
+ body: { goal, ...(where ? { where } : {}), ...(personas ? { personas } : {}), ...(tier ? { tier } : {}), ...(Number.isInteger(minutes) ? { minutes } : {}), ...(runLength ? { run_length: runLength } : {}) }
224
+ }).then(answer => answer.body),
225
+
213
226
  /**
214
227
  * Register a job: this is the request that moves money.
215
228
  *
@@ -385,6 +398,16 @@ export function createClient(options = {}) {
385
398
  ...(Number.isInteger(actionsTaken) ? { actions_taken: actionsTaken } : {})
386
399
  }, true),
387
400
 
401
+ /**
402
+ * The run's recent steps and, while someone watches, one small frame, for
403
+ * the job's live view in the dashboard. Best effort: never retried, an
404
+ * 8 second limit, and free (no unit, no reservation). Answers
405
+ * `{ accepted, watching, intervalMs }`.
406
+ */
407
+ live: (gameId, jobId, runId, body, { timeoutMs = 8000 } = {}) =>
408
+ request('POST', runPath(gameId, jobId, runId, '/live'), { body, retries: 0, timeoutMs })
409
+ .then(answer => answer.body),
410
+
388
411
  uploads: (gameId, jobId, runId, { files, includeVideo = false } = {}) =>
389
412
  request('POST', runPath(gameId, jobId, runId, '/uploads'), {
390
413
  body: { files, include_video: includeVideo }
package/src/cli.js CHANGED
@@ -70,6 +70,11 @@ Run options (parsed by the runner, see src/run/args.js):
70
70
  For a game made for touch; the report says when a game wanted touch and the
71
71
  run was played with a mouse
72
72
  --build-url <url> the web build to play
73
+ --allow-network a browser build only: let this run reach the hosts your game lists under Playtest,
74
+ Network in the dashboard, over https and wss, and nothing else outside the build.
75
+ Off unless given. The report lists the hosts it reached and what was blocked.
76
+ A Godot, desktop or native game is its own program on this machine and cannot be
77
+ limited this way, so the flag is refused for it. It costs the same
73
78
  --url <url> playtest a live web game by its address (staging or production) on this machine. A
74
79
  public host must be verified for the game first (a TXT record, from the Playtest page,
75
80
  Test a live URL); localhost and private addresses are a local dev server and need none.
@@ -130,6 +135,9 @@ Run options (parsed by the runner, see src/run/args.js):
130
135
  --no-replay do not play the findings' recorded inputs again after the report. A replay makes no model
131
136
  call and costs nothing; it opens the game again for a few seconds (a second browser for a
132
137
  web build, a second Godot for a lockstep run)
138
+ --no-live send nothing to the job's Watch live tab while the run plays. By default a run that
139
+ uploads sends its recent steps, and a small picture of the screen while someone watches.
140
+ It costs nothing and never slows the run; --dry-upload and --no-upload-step-log turn it off too
133
141
  --dry-upload list every file and byte that would be sent, send nothing
134
142
  --key-modifier <name> meta or control: the modifier for editing shortcuts in the browser, default the platform's own
135
143
  --headed show the browser
@@ -405,6 +413,17 @@ export function buildProgram() {
405
413
  return personas(flagsFrom(options, { game: options.game }));
406
414
  }));
407
415
 
416
+ common(program.command('setup').description('set up your first playtest step by step: link a game, pick where it runs, say what to learn, see the plan and its price, write the brief and start it'))
417
+ .option('--game <gameId>', 'the game to link')
418
+ .addOption(new Option('--where <place>', 'where it runs: local, cloud or url (default: Ravensight recommends one)').choices(['local', 'cloud', 'url']))
419
+ .option('--goal <text>', 'what you want to learn, such as "can a new player finish the first level"')
420
+ .option('--personas <list>', 'persona slugs to use instead of the suggestion, comma separated')
421
+ .option('--force', 'relink a repo that is already linked to another game')
422
+ .action(capture(slot, async options => {
423
+ const { setup } = await import('./commands/setup.js');
424
+ return setup(flagsFrom(options, { game: options.game, where: options.where, goal: options.goal, personas: options.personas, force: Boolean(options.force) }));
425
+ }));
426
+
408
427
  common(program.command('init').description('link this repo to a Ravensight game'))
409
428
  .option('--game <gameId>', 'the game to link')
410
429
  .option('--force', 'relink a repo that is already linked')
@@ -8,6 +8,7 @@ import { backendName } from '../auth/keychain.js';
8
8
  import { missingScopes } from '../auth/scopes.js';
9
9
  import { loadConfig } from '../config.js';
10
10
  import { packs } from '../packs/index.js';
11
+ import { verifyPack } from '../packs/signature.js';
11
12
  import { detectFfmpeg, freeBytes, recommendConcurrency } from '../detect.js';
12
13
  import { inspectGodot } from '../godot.js';
13
14
  import { CLI_VERSION, compareVersions } from '../version.js';
@@ -616,12 +617,14 @@ export async function runChecks(flags = {}, deps = {}) {
616
617
  try {
617
618
  pack = await packs.get({ api: authed, gameId, modules });
618
619
  const manifest = (await authed.packs.manifest()).body;
620
+ // The manifest is signed too; one that does not verify fails this row with the signature's own message.
621
+ verifyPack(manifest, { apiUrl, expect: { typ: 'playtest-pack/manifest' }, fresh: true });
619
622
  const verified = packs.verifyAgainstManifest(manifest, pack.bundle);
620
623
  rows.push(row(
621
624
  'content pack',
622
625
  verified.ok ? 'pass' : 'fail',
623
626
  verified.ok
624
- ? `${plural(pack.bundle.personas.length, 'persona')}, ${plural(verified.checked, 'component')} verified${pack.stale ? ' (cached)' : ''}`
627
+ ? `${plural(pack.bundle.personas.length, 'persona')}, ${plural(verified.checked, 'component')} verified, signed by Ravensight${pack.stale ? ' (cached)' : ''}`
625
628
  : `these components do not match the manifest: ${verified.mismatched.join(', ')}`,
626
629
  verified.ok ? null : `delete ${paths.packCacheDir(apiUrl)} and run check again`
627
630
  ));
@@ -630,7 +633,7 @@ export async function runChecks(flags = {}, deps = {}) {
630
633
  'content pack',
631
634
  'fail',
632
635
  error instanceof ApiError ? error.message : String(error && error.message),
633
- 'the CLI cannot run without personas and schemas'
636
+ (error && error.hint) || 'the CLI cannot run without personas and schemas'
634
637
  ));
635
638
  }
636
639
  const available = pack && pack.bundle && Array.isArray(pack.bundle.personas) ? pack.bundle.personas : null;
@@ -22,6 +22,7 @@ import { stopRunningChecks } from '../run/checks.js';
22
22
  import { detectGodotBinary, measureProject } from '../run/drivers/godot-project.js';
23
23
  import { claimSignal } from '../run/liveWork.js';
24
24
  import { createHeartbeat } from '../run/heartbeat.js';
25
+ import { createLiveFeed, liveDecision, liveLine } from '../run/liveFeed.js';
25
26
  import { createUsageLedger } from '../run/usage.js';
26
27
  import { configureSpendHold, createModelClient, ModelUnavailableError, ProxyError } from '../run/model.js';
27
28
  import { jobDir, runDir as runDirFor, JOB_FILES, RUN_FILES } from '../run/paths.js';
@@ -46,6 +47,7 @@ import { serveBuildDir } from '../run/serveBuild.js';
46
47
  import { stepLogSetting, stepLogUploadsLine } from '../config.js';
47
48
  import { readLiveSite } from '../run/livesite/options.js';
48
49
  import { domainCheckRefusal, finishLiveSiteRun, pinRefusal } from '../run/livesite/run.js';
50
+ import { finishNetworkRun, networkRefusal, NETWORK_NOT_GRANTED } from '../run/networkRun.js';
49
51
  import { redactingLog, redactValue } from '../run/redaction.js';
50
52
 
51
53
  /**
@@ -187,6 +189,11 @@ async function run(flags, injected, deps, log) {
187
189
  const stepLog = stepLogDecision(options, context.config);
188
190
  options.uploadTranscript = stepLog.upload;
189
191
  log(stepLogLine(stepLog));
192
+ // The job's live view while a run plays (../run/liveFeed.js): on when the run uploads.
193
+ const liveView = liveDecision(options);
194
+ options.live = liveView.on;
195
+ // A dry upload already says it sends nothing; one more line naming it would only repeat that.
196
+ if (liveView.reason !== 'dry_upload') log(liveLine(liveView));
190
197
  const scopeRefusal = await tokenScopeRefusal(api);
191
198
  if (scopeRefusal !== null) {
192
199
  log(scopeRefusal.message);
@@ -200,6 +207,9 @@ async function run(flags, injected, deps, log) {
200
207
  const keyModifier = resolveKeyModifier(options.keyModifier);
201
208
  if (keyModifier.error) { log(keyModifier.error); return EXIT.ENVIRONMENT; }
202
209
  const driverName = options.driver || (context.config && context.config.driver) || 'playwright_web';
210
+ // --allow-network: a browser build's run only, refused before anything is priced (../run/networkRun.js).
211
+ const netRefusal = networkRefusal(options, driverName);
212
+ if (netRefusal) { log(netRefusal); return EXIT.ENVIRONMENT; }
203
213
  if (options.liveSite && driverName !== 'playwright_web') {
204
214
  log(`--url plays a web page in the browser, so it uses the playwright_web driver, not ${driverName}. Nothing was registered or charged.`);
205
215
  return EXIT.ENVIRONMENT;
@@ -425,7 +435,9 @@ async function run(flags, injected, deps, log) {
425
435
  repo: { commit: (context.config && context.config.commit) || '', dirty: Boolean(context.config && context.config.dirty) },
426
436
  max_actions: Number.isInteger(options.maxActions) ? options.maxActions : null,
427
437
  ...(runLength !== 'standard' ? { run_length: runLength } : {}),
428
- pack_versions: { pack: pack.pack_version }
438
+ pack_versions: { pack: pack.pack_version },
439
+ // The server records the game's listed hosts on the job and answers them: those, and only those, are reached.
440
+ ...(options.allowNetwork ? { network: true } : {})
429
441
  }, { idempotencyKey });
430
442
  } catch (error) {
431
443
  const handled = explainRegisterRefusal(error, log);
@@ -434,6 +446,9 @@ async function run(flags, injected, deps, log) {
434
446
  }
435
447
 
436
448
  const jobId = registered.job_id;
449
+ // The hosts this job may reach, as the server recorded them (never the flag's own idea of them).
450
+ options.network = registered.network && Array.isArray(registered.network.hosts) ? { hosts: registered.network.hosts } : null;
451
+ if (options.allowNetwork && !options.network) log(NETWORK_NOT_GRANTED);
437
452
  const directory = jobDir(repoRoot, jobId);
438
453
  await mkdir(directory, { recursive: true });
439
454
 
@@ -464,7 +479,9 @@ async function run(flags, injected, deps, log) {
464
479
  uploadVideo: Boolean(options.uploadVideo),
465
480
  uploadTranscript: Boolean(options.uploadTranscript),
466
481
  // A live site run: where it starts and how it signs in, never a secret (resume asks for the same flags).
467
- ...(options.liveSite ? { liveUrl: liveSiteRecord(options.liveSite) } : {})
482
+ ...(options.liveSite ? { liveUrl: liveSiteRecord(options.liveSite) } : {}),
483
+ // The hosts the job was given at register: a resume reaches the same ones.
484
+ ...(options.network ? { network: options.network } : {})
468
485
  }
469
486
  });
470
487
  for (const entry of registered.runs || []) {
@@ -547,6 +564,11 @@ export function explainRegisterRefusal(error, log) {
547
564
  log('The server refused this job because the game has no complete expectations brief. Run "ravensight-playtest brief" and try again.');
548
565
  return EXIT.ENVIRONMENT;
549
566
  }
567
+ // --allow-network on a game that lists no hosts: the server says so before any charge, in its own words.
568
+ if (code === 'network_hosts_empty') {
569
+ log(`${body.message || 'This game lists no hosts its playtests may reach. Nothing was charged.'} Add them in the dashboard under Playtest, Network, or run without --allow-network.`);
570
+ return EXIT.ENVIRONMENT;
571
+ }
550
572
  if (code === 'insufficient_balance' && Number.isFinite(body.minimum_balance_cents)) {
551
573
  log(startBalanceShort(body));
552
574
  return EXIT.ENVIRONMENT;
@@ -902,7 +924,7 @@ export async function playPersonaRun({
902
924
  const runTarget = entry.target || target;
903
925
  let driver;
904
926
  try {
905
- driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl }));
927
+ driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null }));
906
928
  } catch (error) {
907
929
  // A driver that cannot even be built (the browser package missing, say) is
908
930
  // what a new machine hits first. The run is completed as failed now, with
@@ -950,6 +972,11 @@ export async function playPersonaRun({
950
972
  onError: () => {}
951
973
  });
952
974
  heartbeat.start();
975
+ // Created now, posts nothing until the play loop hands it a step, which is after `playing` was accepted.
976
+ // A test seam, `deps.createLiveFeed`, stands in for the feed; an API surface with no live call has none.
977
+ const live = options.live === true && (deps.createLiveFeed || (api.runs && typeof api.runs.live === 'function'))
978
+ ? (deps.createLiveFeed || createLiveFeed)({ api, gameId, jobId, runId })
979
+ : null;
953
980
 
954
981
  let outcome;
955
982
  try {
@@ -982,13 +1009,14 @@ export async function playPersonaRun({
982
1009
  schemas: pack.schemas || [],
983
1010
  maxActions,
984
1011
  heartbeat,
1012
+ live,
985
1013
  ledger,
986
1014
  memory,
987
1015
  recordVideo: recordingMode(options, driverName),
988
1016
  edgePass: options.noEdgePass !== true,
989
1017
  replayFindings: options.noReplay !== true,
990
1018
  // A web run's findings are replayed in a second browser of the same kind, on the same target, with no recording.
991
- ...(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, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl })) } : {}),
1019
+ ...(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, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null })) } : {}),
992
1020
  // A run sold by the minute stops on the clock (../run/playClock.js).
993
1021
  playClock: playClockFor(options, entry),
994
1022
  ...(options.phone === true && driverName === 'playwright_web' ? { viewport: PHONE_VIEWPORT } : {}),
@@ -1005,6 +1033,7 @@ export async function playPersonaRun({
1005
1033
  });
1006
1034
  } catch (error) {
1007
1035
  heartbeat.stop();
1036
+ if (live) live.close();
1008
1037
  if (options.signal?.aborted) {
1009
1038
  await stateFile.patchRun(repoRoot, journal, runId, { state: 'interrupted', completed: false, actions_taken: error.outcome?.actionsTaken || 0 });
1010
1039
  return { runId, persona: persona.slug, state: 'interrupted', error };
@@ -1037,6 +1066,7 @@ export async function playPersonaRun({
1037
1066
  });
1038
1067
  // A live site run's report, step log and usage are scanned for its sign-in secrets before anything is sent.
1039
1068
  await finishLiveSiteRun({ directory, driver, outcome: failed, liveSite: options.liveSite || null });
1069
+ await finishNetworkRun({ directory, driver, outcome: failed });
1040
1070
  const delivery = {};
1041
1071
  const answer = await deliver({ deps, api, gameId, jobId, runId, directory, outcome: failed, options, log, repoRoot, delivery });
1042
1072
  // The server finishes a run that played past the proof bar and then reached
@@ -1092,6 +1122,7 @@ export async function playPersonaRun({
1092
1122
  return { runId, persona: persona.slug, state: failed.state, quitReason: failed.quitReason, error };
1093
1123
  }
1094
1124
  heartbeat.stop();
1125
+ if (live) live.close();
1095
1126
  if (options.signal?.aborted) {
1096
1127
  await stateFile.patchRun(repoRoot, journal, runId, { state: 'interrupted', completed: false, actions_taken: outcome.actionsTaken, report_written: Boolean(outcome.report) });
1097
1128
  return { runId, persona: persona.slug, state: 'interrupted' };
@@ -1099,6 +1130,8 @@ export async function playPersonaRun({
1099
1130
  if (inFlight) inFlight.delete(runId);
1100
1131
  // A live site run's report, step log and usage are scanned for its sign-in secrets before anything is sent.
1101
1132
  await finishLiveSiteRun({ directory, driver, outcome, liveSite: options.liveSite || null });
1133
+ // A run with network access: the report's Network section and usage.json `network` (../run/networkRun.js).
1134
+ await finishNetworkRun({ directory, driver, outcome });
1102
1135
 
1103
1136
  await stateFile.patchRun(repoRoot, journal, runId, {
1104
1137
  state: outcome.state,
@@ -1822,7 +1855,7 @@ export async function resolveSetup(deps, options, log) {
1822
1855
  *
1823
1856
  * @returns {Object}
1824
1857
  */
1825
- export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null }) {
1858
+ export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null, network = null }) {
1826
1859
  // Only the browser driver sends key chords with a modifier.
1827
1860
  const modifier = driverName === 'playwright_web' ? resolveKeyModifier(keyModifier).modifier : null;
1828
1861
  const godot = driverName === 'godot_driver'
@@ -1841,6 +1874,8 @@ export function driverOptions({ headless, driverName, target, directory, entry,
1841
1874
  ...(driverName === 'playwright_web' && phone === true ? { touch: true } : {}),
1842
1875
  // A live URL run (../run/livesite/): its network rules, sign-in and masking.
1843
1876
  ...(driverName === 'playwright_web' && liveSite ? { liveSite } : {}),
1877
+ // Network access: the hosts the job was given at register (../run/egress.js). A browser build only.
1878
+ ...(driverName === 'playwright_web' && network && !liveSite ? { network } : {}),
1844
1879
  // The Ravensight ingest origins the game's own SDK session can go to: the SDKs' default and this run's API (../run/sdkSession.js).
1845
1880
  ...(driverName === 'playwright_web' && apiUrl ? { ingestOrigins: ingestOriginsFor(apiUrl) } : {}),
1846
1881
  ...godot,
@@ -0,0 +1,176 @@
1
+ import { createContext } from '../api/index.js';
2
+ import { withAuthHandling } from '../auth/session.js';
3
+ import { loadConfig } from '../config.js';
4
+ import { ui } from '../ui/index.js';
5
+ import { CliError, ExitCode } from '../errors.js';
6
+ import { init } from './init.js';
7
+ import { askQuickBrief, completenessFor, createPrompter, saveBrief } from './brief.js';
8
+
9
+ /** The places a playtest can run, in the order `setup` offers them. */
10
+ export const PLACES = Object.freeze([
11
+ { where: 'local', label: 'On this computer (web, Godot or a native mobile build)' },
12
+ { where: 'cloud', label: 'In the Ravensight cloud (an uploaded web build, nothing to install)' },
13
+ { where: 'url', label: 'A live web address, played in the Ravensight cloud' }
14
+ ]);
15
+
16
+ const MAX_GOAL_CHARS = 500;
17
+
18
+ /**
19
+ * `ravensight-playtest setup`: the guided first playtest.
20
+ *
21
+ * Links this repo to a game (the init path), asks where the game should run
22
+ * and what the studio wants to learn, and shows the server's plan for it:
23
+ * the personas, what the brief still needs and the price, from the same
24
+ * pricing the real quote uses. It can write the brief with the plan's
25
+ * suggestions filled in, and for a local run hand over to `run`, which shows
26
+ * the price again and asks before anything is charged. Nothing in this
27
+ * command charges: a plan is free and a cloud run ends with the commands that
28
+ * save its quote, which is that run's own consent.
29
+ *
30
+ * `--yes` is never passed on to `run`: consent to a price is asked there.
31
+ *
32
+ * @param {{game?: string, where?: string, goal?: string, personas?: string, json?: boolean, repoRoot?: string, apiUrl?: string}} flags
33
+ * @param {{context?: Object, ask?: Function, choose?: Function, confirm?: Function, runCommand?: Function, init?: Function}} [deps]
34
+ * @returns {Promise<number>}
35
+ */
36
+ export async function setup(flags = {}, deps = {}) {
37
+ const repoRoot = flags.repoRoot || process.cwd();
38
+ const context = deps.context || await createContext({ apiUrl: flags.apiUrl, repoRoot, requireAuth: true });
39
+ return withAuthHandling(context, () => guide(context, { ...flags, repoRoot }, deps));
40
+ }
41
+
42
+ async function guide(context, flags, deps) {
43
+ const choose = deps.choose || ui.choose;
44
+ const confirm = deps.confirm || ui.confirm;
45
+ // One readline for the whole guide, opened on the first question only.
46
+ let prompter = null;
47
+ const ask = deps.ask || (question => (prompter ||= createPrompter()).ask(question));
48
+ const canAsk = Boolean(deps.ask) || process.stdin.isTTY === true;
49
+ try {
50
+ if (flags.where !== undefined && !PLACES.some(place => place.where === flags.where)) {
51
+ throw new CliError(`--where must be one of ${PLACES.map(place => place.where).join(', ')}.`, ExitCode.FAILURE);
52
+ }
53
+
54
+ // 1. The game. A linked repo keeps its link; otherwise init links it, asking on a terminal.
55
+ const gameId = await linkedGame(context, flags, deps);
56
+ if (!flags.json) ui.ok(`Step 1 of 4: this repo plays ${gameId}.`);
57
+
58
+ // 2. Where it runs. No answer (no terminal) lets the plan recommend one.
59
+ let where = flags.where;
60
+ if (!where && !flags.json) {
61
+ const picked = await choose('Where should your game run? [1-3, Enter to let Ravensight recommend]', PLACES.map(place => place.label));
62
+ if (Number.isInteger(picked) && PLACES[picked]) where = PLACES[picked].where;
63
+ }
64
+
65
+ // 3. What to learn.
66
+ let goal = typeof flags.goal === 'string' ? flags.goal.trim() : '';
67
+ if (!goal && !flags.json && canAsk) goal = String(await ask('What do you want to learn from this playtest? ') || '').trim();
68
+ if (!goal) throw new CliError('Say what you want to learn.', ExitCode.FAILURE, { hint: 'ravensight-playtest setup --goal "can a new player finish the first level"' });
69
+ if (goal.length > MAX_GOAL_CHARS) throw new CliError(`Keep the goal to ${MAX_GOAL_CHARS} characters.`, ExitCode.FAILURE);
70
+
71
+ const personas = typeof flags.personas === 'string' && flags.personas.trim()
72
+ ? flags.personas.split(',').map(slug => slug.trim()).filter(Boolean)
73
+ : undefined;
74
+ const plan = await context.api.jobs.plan(gameId, { goal, ...(where ? { where } : {}), ...(personas ? { personas } : {}) });
75
+ if (flags.json) {
76
+ ui.json(plan);
77
+ return ExitCode.OK;
78
+ }
79
+
80
+ const option = plan.options.find(entry => entry.where === (where || plan.recommended)) || plan.options[0];
81
+ showPlan(plan, option, Boolean(where));
82
+
83
+ // 4. The brief, when it is not complete: the plan's suggestions are the starting answers.
84
+ let briefReady = plan.brief.status === 'complete';
85
+ if (!briefReady) {
86
+ ui.blank();
87
+ ui.warn(`Step 3 of 4: the expectations brief is ${plan.brief.status}. A playtest needs one: it tells the personas what the game is for.`);
88
+ if (await confirm('Write it now? Press Enter on a question to keep the suggestion.', { noTerminalMessage: 'No terminal to ask in. Run "ravensight-playtest brief" to write the brief.' })) {
89
+ briefReady = await writeBrief(context, gameId, plan.brief, { ask }, flags);
90
+ }
91
+ } else {
92
+ ui.ok('Step 3 of 4: the expectations brief is complete.');
93
+ }
94
+
95
+ ui.blank();
96
+ if (option.where === 'local' && briefReady && option.available !== false) {
97
+ ui.info('Step 4 of 4: start it. The run shows the price again and asks you to confirm before anything is charged.');
98
+ if (await confirm('Start this playtest now?', { noTerminalMessage: 'No terminal to ask in. Start it with the command above.' })) {
99
+ const runCommand = deps.runCommand || (await import('../run/index.js')).runCommand;
100
+ // Never --yes: the price is confirmed in run, by the person.
101
+ const { yes: _yes, ...rest } = flags;
102
+ return runCommand({ ...rest, game: gameId, argv: ['--personas', option.run.personas.join(','), ...(option.run.run_length === 'long' ? ['--long'] : [])] });
103
+ }
104
+ ui.info('Nothing was started or charged. Run the last command above when you are ready.');
105
+ return ExitCode.OK;
106
+ }
107
+ ui.info('Step 4 of 4: when you are ready, run the commands above in order. Nothing was started or charged.');
108
+ return ExitCode.OK;
109
+ } finally {
110
+ if (prompter) prompter.close();
111
+ }
112
+ }
113
+
114
+ /** The repo's game: the --game flag or the link, else init links it now. */
115
+ async function linkedGame(context, flags, deps) {
116
+ const config = context.config || await loadConfig({ repoRoot: flags.repoRoot });
117
+ if (config && config.game_id && (!flags.game || flags.game === config.game_id)) return config.game_id;
118
+ const link = deps.init || init;
119
+ await link({ game: flags.game, repoRoot: flags.repoRoot, apiUrl: flags.apiUrl, force: Boolean(flags.force) }, { context, ...(deps.choose ? { choose: deps.choose } : {}) });
120
+ const linked = await loadConfig({ repoRoot: flags.repoRoot });
121
+ if (!linked || !linked.game_id) throw new CliError('This repo is not linked to a game.', ExitCode.FAILURE, { hint: 'ravensight-playtest init --game <gameId>' });
122
+ return linked.game_id;
123
+ }
124
+
125
+ /** "$1.00", or "not priced" when the option has no quote. */
126
+ function price(quote) {
127
+ return quote && Number.isInteger(quote.estimate_cents) ? ui.money(quote.estimate_cents) : 'not priced';
128
+ }
129
+
130
+ function showPlan(plan, option, chosen) {
131
+ ui.blank();
132
+ ui.ok(`Step 2 of 4: ${chosen ? 'the plan' : `Ravensight recommends ${PLACES.find(place => place.where === option.where).label.toLowerCase()}`}.`);
133
+ ui.info(option.why);
134
+ if (option.available === false) return;
135
+ ui.info(`Personas: ${plan.personas.map(persona => `${persona.name} (${persona.slug})`).join(', ')}${option.where === 'local' ? '' : ', with fresh-eyes always included in the cloud'}.`);
136
+ ui.info(`Playtester: ${option.run.playtester}.`);
137
+ ui.info(ui.bold(`Price: ${price(option.quote)}${option.quote && option.quote.per_persona_cents ? ` (${ui.money(option.quote.per_persona_cents)} a persona on the ${option.quote.tier} tier, ${option.quote.minutes} minutes)` : ''}.`));
138
+ if (option.quote && option.quote.note) ui.info(option.quote.note);
139
+ if (option.quote && option.quote.ok === false) ui.warn(`That is more than the balance covers. Top up at ${option.quote.topup_url || 'ravensight.io'} first.`);
140
+ for (const other of plan.options.filter(entry => entry !== option && entry.available !== false)) {
141
+ ui.info(`Also possible: ${other.where}, ${price(other.quote)}.`);
142
+ }
143
+ ui.blank();
144
+ ui.info('To start it:');
145
+ option.next_steps.forEach((step, index) => ui.info(` ${index + 1}. ${step.say}${step.command ? `\n ${step.command}` : ''}${step.dashboard_path ? ` (the dashboard, ${step.dashboard_path})` : ''}`));
146
+ ui.info(plan.consent);
147
+ }
148
+
149
+ /** Ask the quick brief with the plan's suggestions as answers to keep, and save it. */
150
+ async function writeBrief(context, gameId, planned, io, flags) {
151
+ const current = await context.api.brief.get(gameId);
152
+ const existing = current && current.brief ? current.brief.fields : {};
153
+ // What the brief already says wins; the plan fills only what is empty.
154
+ const suggested = planned.suggested_fields || {};
155
+ const seed = {
156
+ ...existing,
157
+ goals: Array.isArray(existing.goals) && existing.goals.length ? existing.goals : suggested.goals || [],
158
+ success_criteria: typeof existing.success_criteria === 'string' && existing.success_criteria.trim() ? existing.success_criteria : suggested.success_criteria || ''
159
+ };
160
+ const fields = await askQuickBrief(seed, io);
161
+ const complete = completenessFor(fields).complete;
162
+ const saved = await saveBrief({
163
+ api: context.api,
164
+ gameId,
165
+ fields,
166
+ status: complete ? 'complete' : 'draft',
167
+ parentVersion: current && current.brief ? current.brief.version : null,
168
+ onStale: async version => {
169
+ ui.warn(`The brief moved to version ${version} while you were writing.`);
170
+ return ui.confirm('Save on top of that version?', { yes: flags.yes, noTerminalMessage: 'No terminal to confirm in. Run "ravensight-playtest brief" again.' });
171
+ }
172
+ });
173
+ ui.ok(`Saved brief version ${saved.brief.version} (${saved.brief.status}).`);
174
+ if (!complete) ui.warn(`Still missing: ${completenessFor(fields).missing.join(', ')}. Run "ravensight-playtest brief" to finish it.`);
175
+ return complete;
176
+ }