ravensight-playtest 0.13.2 → 0.16.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 (40) hide show
  1. package/README.md +99 -4
  2. package/addons/ravensight_driver/driver.gd +472 -28
  3. package/docs/godot-driver.md +66 -2
  4. package/package.json +7 -5
  5. package/src/api/README.md +8 -1
  6. package/src/api/client.js +24 -1
  7. package/src/cli.js +14 -0
  8. package/src/commands/check.js +5 -2
  9. package/src/commands/fix.js +1 -1
  10. package/src/commands/run.js +26 -4
  11. package/src/commands/setup.js +176 -0
  12. package/src/packs/index.js +37 -5
  13. package/src/packs/keys.json +11 -0
  14. package/src/packs/pack-signing-hashes.json +7 -0
  15. package/src/packs/pack-signing-vectors.json +119 -0
  16. package/src/packs/signature.js +186 -0
  17. package/src/run/anygame/gamenotes.js +74 -12
  18. package/src/run/anygame/index.js +97 -34
  19. package/src/run/anygame/language.js +100 -10
  20. package/src/run/anygame/memory.js +70 -13
  21. package/src/run/anygame/shared-hashes.json +7 -7
  22. package/src/run/anygame/sound.js +59 -16
  23. package/src/run/args.js +2 -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 +124 -14
  29. package/src/run/eventclaims.js +102 -6
  30. package/src/run/events.js +64 -6
  31. package/src/run/gameMemory.js +14 -5
  32. package/src/run/honesty.js +49 -2
  33. package/src/run/judge.js +22 -10
  34. package/src/run/liveFeed.js +254 -0
  35. package/src/run/personaLoop.js +103 -25
  36. package/src/run/pixels.js +491 -2
  37. package/src/run/replay.js +11 -0
  38. package/src/run/sdkSession.js +279 -16
  39. package/src/run/synthetic.js +12 -8
  40. 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.2",
3
+ "version": "0.16.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,13 +49,15 @@
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.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.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",
58
- "test:ios": "node scripts/gated-test.mjs RAVENSIGHT_IOS_E2E all -- --test --test-timeout=240000 --test-concurrency=1 src/run/drivers/mobile/native-real.test.js"
58
+ "test:ios": "node scripts/gated-test.mjs RAVENSIGHT_IOS_E2E all -- --test --test-timeout=240000 --test-concurrency=1 src/run/drivers/mobile/native-real.test.js",
59
+ "hooks:install": "git config core.hooksPath .githooks",
60
+ "prepare": "node -e \"try{require('child_process').execFileSync('git',['config','core.hooksPath','.githooks'],{stdio:'ignore'})}catch(e){}\""
59
61
  },
60
62
  "dependencies": {
61
63
  "ajv": "^8.17.1",
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
@@ -130,6 +130,9 @@ Run options (parsed by the runner, see src/run/args.js):
130
130
  --no-replay do not play the findings' recorded inputs again after the report. A replay makes no model
131
131
  call and costs nothing; it opens the game again for a few seconds (a second browser for a
132
132
  web build, a second Godot for a lockstep run)
133
+ --no-live send nothing to the job's Watch live tab while the run plays. By default a run that
134
+ uploads sends its recent steps, and a small picture of the screen while someone watches.
135
+ It costs nothing and never slows the run; --dry-upload and --no-upload-step-log turn it off too
133
136
  --dry-upload list every file and byte that would be sent, send nothing
134
137
  --key-modifier <name> meta or control: the modifier for editing shortcuts in the browser, default the platform's own
135
138
  --headed show the browser
@@ -405,6 +408,17 @@ export function buildProgram() {
405
408
  return personas(flagsFrom(options, { game: options.game }));
406
409
  }));
407
410
 
411
+ 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'))
412
+ .option('--game <gameId>', 'the game to link')
413
+ .addOption(new Option('--where <place>', 'where it runs: local, cloud or url (default: Ravensight recommends one)').choices(['local', 'cloud', 'url']))
414
+ .option('--goal <text>', 'what you want to learn, such as "can a new player finish the first level"')
415
+ .option('--personas <list>', 'persona slugs to use instead of the suggestion, comma separated')
416
+ .option('--force', 'relink a repo that is already linked to another game')
417
+ .action(capture(slot, async options => {
418
+ const { setup } = await import('./commands/setup.js');
419
+ return setup(flagsFrom(options, { game: options.game, where: options.where, goal: options.goal, personas: options.personas, force: Boolean(options.force) }));
420
+ }));
421
+
408
422
  common(program.command('init').description('link this repo to a Ravensight game'))
409
423
  .option('--game <gameId>', 'the game to link')
410
424
  .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;
@@ -1177,7 +1177,7 @@ export async function runVerify({
1177
1177
  return null;
1178
1178
  }
1179
1179
  const headless = driverName === 'godot_driver' ? options.headless === true : options.headed !== true;
1180
- const driver = await makeDriver(driverName, driverOptions({ headless, driverName, target, directory, entry, jobId, godotPath: options.godotPath, realtime: options.realtime }));
1180
+ const driver = await makeDriver(driverName, driverOptions({ headless, driverName, target, directory, entry, jobId, godotPath: options.godotPath, realtime: options.realtime, apiUrl: api && api.apiUrl ? api.apiUrl : null }));
1181
1181
  const ledger = createUsageLedger();
1182
1182
  const heartbeat = createHeartbeat({
1183
1183
  api,
@@ -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';
@@ -41,6 +42,7 @@ import { bold } from '../ui/index.js';
41
42
  import { reconcileDroppedFindings } from '../run/dropped.js';
42
43
  import * as stateFile from '../run/state.js';
43
44
  import { emitRunEvents } from '../run/synthetic.js';
45
+ import { ingestOriginsFor, playtestTagLine } from '../run/sdkSession.js';
44
46
  import { serveBuildDir } from '../run/serveBuild.js';
45
47
  import { stepLogSetting, stepLogUploadsLine } from '../config.js';
46
48
  import { readLiveSite } from '../run/livesite/options.js';
@@ -186,6 +188,11 @@ async function run(flags, injected, deps, log) {
186
188
  const stepLog = stepLogDecision(options, context.config);
187
189
  options.uploadTranscript = stepLog.upload;
188
190
  log(stepLogLine(stepLog));
191
+ // The job's live view while a run plays (../run/liveFeed.js): on when the run uploads.
192
+ const liveView = liveDecision(options);
193
+ options.live = liveView.on;
194
+ // A dry upload already says it sends nothing; one more line naming it would only repeat that.
195
+ if (liveView.reason !== 'dry_upload') log(liveLine(liveView));
189
196
  const scopeRefusal = await tokenScopeRefusal(api);
190
197
  if (scopeRefusal !== null) {
191
198
  log(scopeRefusal.message);
@@ -901,7 +908,7 @@ export async function playPersonaRun({
901
908
  const runTarget = entry.target || target;
902
909
  let driver;
903
910
  try {
904
- 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 }));
911
+ 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 }));
905
912
  } catch (error) {
906
913
  // A driver that cannot even be built (the browser package missing, say) is
907
914
  // what a new machine hits first. The run is completed as failed now, with
@@ -949,6 +956,11 @@ export async function playPersonaRun({
949
956
  onError: () => {}
950
957
  });
951
958
  heartbeat.start();
959
+ // Created now, posts nothing until the play loop hands it a step, which is after `playing` was accepted.
960
+ // A test seam, `deps.createLiveFeed`, stands in for the feed; an API surface with no live call has none.
961
+ const live = options.live === true && (deps.createLiveFeed || (api.runs && typeof api.runs.live === 'function'))
962
+ ? (deps.createLiveFeed || createLiveFeed)({ api, gameId, jobId, runId })
963
+ : null;
952
964
 
953
965
  let outcome;
954
966
  try {
@@ -981,13 +993,14 @@ export async function playPersonaRun({
981
993
  schemas: pack.schemas || [],
982
994
  maxActions,
983
995
  heartbeat,
996
+ live,
984
997
  ledger,
985
998
  memory,
986
999
  recordVideo: recordingMode(options, driverName),
987
1000
  edgePass: options.noEdgePass !== true,
988
1001
  replayFindings: options.noReplay !== true,
989
1002
  // A web run's findings are replayed in a second browser of the same kind, on the same target, with no recording.
990
- ...(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 })) } : {}),
1003
+ ...(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 })) } : {}),
991
1004
  // A run sold by the minute stops on the clock (../run/playClock.js).
992
1005
  playClock: playClockFor(options, entry),
993
1006
  ...(options.phone === true && driverName === 'playwright_web' ? { viewport: PHONE_VIEWPORT } : {}),
@@ -1004,6 +1017,7 @@ export async function playPersonaRun({
1004
1017
  });
1005
1018
  } catch (error) {
1006
1019
  heartbeat.stop();
1020
+ if (live) live.close();
1007
1021
  if (options.signal?.aborted) {
1008
1022
  await stateFile.patchRun(repoRoot, journal, runId, { state: 'interrupted', completed: false, actions_taken: error.outcome?.actionsTaken || 0 });
1009
1023
  return { runId, persona: persona.slug, state: 'interrupted', error };
@@ -1091,6 +1105,7 @@ export async function playPersonaRun({
1091
1105
  return { runId, persona: persona.slug, state: failed.state, quitReason: failed.quitReason, error };
1092
1106
  }
1093
1107
  heartbeat.stop();
1108
+ if (live) live.close();
1094
1109
  if (options.signal?.aborted) {
1095
1110
  await stateFile.patchRun(repoRoot, journal, runId, { state: 'interrupted', completed: false, actions_taken: outcome.actionsTaken, report_written: Boolean(outcome.report) });
1096
1111
  return { runId, persona: persona.slug, state: 'interrupted' };
@@ -1123,14 +1138,19 @@ export async function playPersonaRun({
1123
1138
  ingestKey: (config && config.ingest_key) || process.env.RAVENSIGHT_INGEST_KEY || null,
1124
1139
  playtestToken: entry.playtest_token,
1125
1140
  // The web driver injects the playtest token into the page (see
1126
- // driverOptions), so the game's own SDK sends with it.
1141
+ // driverOptions), so the game's own SDK is the run's telemetry; whether
1142
+ // it carried the tag is said only from the session requests the run saw.
1127
1143
  pageSdk: driverName === 'playwright_web' && Boolean(entry.playtest_token),
1144
+ pageTag: outcome.playtestTag || null,
1128
1145
  context: { jobId, runId, persona: persona.slug, gameVersion: (config && config.game_version) || 'unknown' },
1129
1146
  report: outcome.report,
1130
1147
  driver: driverName,
1131
1148
  log: message => log(`run ${runId}: ${message}`)
1132
1149
  });
1133
1150
  if (emitted.reason) log(`run ${runId}: ${emitted.reason}`);
1151
+ // The CLI sent its own events (an ingest key), but the game's own SDK on the page sent its events untagged: said as well.
1152
+ const tag = outcome.playtestTag;
1153
+ if (!emitted.pageSdk && tag && (tag.state === 'untagged' || tag.state === 'unseen')) log(`run ${runId}: ${playtestTagLine(tag)}`);
1134
1154
  }
1135
1155
 
1136
1156
  // Out of budget while playing, but past the proof bar with its report kept:
@@ -1816,7 +1836,7 @@ export async function resolveSetup(deps, options, log) {
1816
1836
  *
1817
1837
  * @returns {Object}
1818
1838
  */
1819
- export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null }) {
1839
+ export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null }) {
1820
1840
  // Only the browser driver sends key chords with a modifier.
1821
1841
  const modifier = driverName === 'playwright_web' ? resolveKeyModifier(keyModifier).modifier : null;
1822
1842
  const godot = driverName === 'godot_driver'
@@ -1835,6 +1855,8 @@ export function driverOptions({ headless, driverName, target, directory, entry,
1835
1855
  ...(driverName === 'playwright_web' && phone === true ? { touch: true } : {}),
1836
1856
  // A live URL run (../run/livesite/): its network rules, sign-in and masking.
1837
1857
  ...(driverName === 'playwright_web' && liveSite ? { liveSite } : {}),
1858
+ // The Ravensight ingest origins the game's own SDK session can go to: the SDKs' default and this run's API (../run/sdkSession.js).
1859
+ ...(driverName === 'playwright_web' && apiUrl ? { ingestOrigins: ingestOriginsFor(apiUrl) } : {}),
1838
1860
  ...godot,
1839
1861
  playtest: {
1840
1862
  token: entry.playtest_token || null,
@@ -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
+ }