ravensight-playtest 0.13.1 → 0.13.3

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.
package/README.md CHANGED
@@ -719,10 +719,35 @@ game's own events", in `usage.json` `gameEvents.sessionRefused` and on screen,
719
719
  that no game events were recorded and why. Nothing is counted as a player. A
720
720
  cloud playtest of the same build records them.
721
721
 
722
+ Handing the page the playtest identity is not enough on its own: the game's
723
+ SDK has to read it and send it with its session. An SDK from before it read the
724
+ identity (ravensight-js before 0.3.0, for example) opens an ordinary session, and
725
+ every event in it counts as a real player. So a web run reads each session
726
+ request the game's SDK makes: a POST to the session path on the Ravensight API
727
+ this run uses or the SDKs' default ingest address (your game's own backend at
728
+ the same path is left alone). It reads whether the request carried this run's
729
+ own token, with or without a "Bearer " prefix, and the SDK's own name and
730
+ version when the request gives a plain one; never the key, the token or the
731
+ device id. A session that opened without this run's token (or with another
732
+ value) is untagged, and that is said even when another request could not be
733
+ read. The events are called tagged only when every session the SDK opened
734
+ carried this run's token and no session request went unread. When they were
735
+ not tagged, `report.md` says under "Measured from the game's own events" that
736
+ the game's analytics SDK did not tag them and that they count as a real player
737
+ until the game updates its Ravensight SDK, with the SDK version in a code span.
738
+ When the run cannot tell (a session request it could not read, or events with
739
+ no session seen), it says the CLI could not tell whether they were tagged, and
740
+ never that they were. `usage.json` carries
741
+ `gameEvents.playtestTag` (`tagged`, `state`, `countsAs`, the sessions, the
742
+ events, the SDK version or null, and the sentence), the step log a
743
+ `game_events_tag` line, and the run summary says the same.
744
+
722
745
  With no ingest key configured, a Godot run says "no ingest key configured, so
723
- no synthetic telemetry was sent". A web run says "synthetic telemetry comes from
724
- the game's own SDK on the page, sent with the run's playtest token" instead,
725
- because the page's SDK already sends the game's events marked synthetic.
746
+ no synthetic telemetry was sent". A web run says instead what the page's own
747
+ SDK was seen to do: "synthetic telemetry comes from the game's own SDK on the
748
+ page (js/0.12.1), which opened its session with the run's playtest tag", that
749
+ it "did not tag its 23 events as this playtest ... so they count as a real
750
+ player", or that it "sent no events and opened no session".
726
751
 
727
752
  When a run reaches its model budget before the report step, nothing more is
728
753
  asked of the model. The persona's notes are written to a partial `report.json`
@@ -938,6 +963,40 @@ are the driver's, not the game's: they are recorded as `driver_error`, and a
938
963
  blocker or major resting only on them is dropped before upload, as is any
939
964
  finding resting only on the persona's "waiting for X to finish" notes.
940
965
 
966
+ On a game drawn in a canvas the words a player reads are in the picture, not
967
+ in the page, so a click by a label the page does not hold ("New Run", "START
968
+ RUN") is refused at once, well under a second, with where to click instead: the
969
+ label's grid cell, its mark, or its x and y read off the screenshot. A label the
970
+ page does hold (a button around the canvas) is clicked as before. Until 0.13.2
971
+ such a click waited the full 15 second action timeout.
972
+
973
+ Every input the persona sends with `expect` is held against the screen after
974
+ it: the screen not changing at all, a part of the game the run's focus or the
975
+ input said to stay out of ("not the Tutorial") read as the screen's state
976
+ ("TUTORIAL 1/7"), the persona's own answer on its next tool call
977
+ (`intent_check` "met" or "missed", and `instead`, what the screen shows), and
978
+ the same input sent again for the same result. A screen that changed is not
979
+ enough: a key that draws a new line of dialogue each time but never does what
980
+ it was meant to is a miss. An input that missed the same result twice in a row
981
+ is not sent a third time; the persona is told what the screen showed instead
982
+ and asked for a different approach (move first with the arrow keys or W A S D,
983
+ click another target). An input that moves the game on a step at a time (the
984
+ next page of a story, the next tip dismissed) is never counted as a miss from
985
+ the record alone. Each answer, miss and refused repeat is an `intent_check` or
986
+ `intent_refused` line of the step log, the action list the report step reads
987
+ says which inputs missed, and `usage.json` carries the record as `intent`.
988
+
989
+ `report.md` says what was played under its title (**What was played**, in the
990
+ cloud report's words): a run that used its action or model budget "played to
991
+ its budget" and is never said to have stopped early, the furthest point the
992
+ persona confirmed or moved on from, the result it aimed at and never reached
993
+ with what the screen showed instead, a part of the game the focus said to stay
994
+ out of, and the game's own events. `usage.json` carries the same as `scope`.
995
+ The in-character section is held to the run's record: a sentence saying the
996
+ persona walked or moved to a result it only ever pressed a non-moving key for,
997
+ or repeating a claim the frames contradicted, is left out, and the record's own
998
+ fact is said instead in a line written by the runner.
999
+
941
1000
  An action counts as changing the screen when the URL changed, the page loaded
942
1001
  a new document, the visible tree (field values included) changed, or for typing,
943
1002
  the field's own value changed, with one short second look for a navigation
@@ -1049,7 +1108,11 @@ The rest of the price is refunded when the job finishes. The CLI prints why the
1049
1108
  run was short and what to try next as soon as the run completes, writes the
1050
1109
  same words into the run's `report.md` under "Why this run was short", and
1051
1110
  prints what was charged and refunded when the job finishes. The dashboard's
1052
- job page shows the same sentences on the run.
1111
+ job page shows the same sentences on the run. A run that played to its budget
1112
+ (its action or model budget, with the report reserve) is never called short or
1113
+ "stopped early": when the server still bills it at cost, the CLI says it played
1114
+ to its budget and writes the server's other words under "How this run was
1115
+ billed" instead.
1053
1116
 
1054
1117
  A run the game itself cut short is charged in full, because that run did its
1055
1118
  job: a blocker the persona reported with evidence, or a persona that quit in
@@ -1349,7 +1412,7 @@ which has to be refreshed by hand whenever the server's schema changes.
1349
1412
 
1350
1413
  | Code | Meaning |
1351
1414
  |---|---|
1352
- | 0 | Success |
1415
+ | 0 | Success. A run that played (at least 15 actions, or every action it had) and wrote its report is a success even when it found nothing and the server settles the job as failed because no run counted as a result. |
1353
1416
  | 1 | Failure |
1354
1417
  | 2 | Budget exceeded during play. Partial results were written and uploaded. A run that ran out during the report step and was completed does not make the job exit 2. |
1355
1418
  | 3 | Environment check failed |
@@ -1848,3 +1911,7 @@ devices and cloud runs of a native build are not available; the cloud still
1848
1911
  needs a web build. The video stays on this machine unless you pass
1849
1912
  `--upload-video`. Prices, budgets and refunds are those of any local persona
1850
1913
  run. Setup, every flag and the limits are in [docs/MOBILE.md](docs/MOBILE.md).
1914
+
1915
+ ## Contributing
1916
+
1917
+ `npm install` installs the local checks (or run `npm run hooks:install`). The pre-push hook then runs the tests on Node 24 before every push, with a time limit, and refuses the push if they fail. CI runs nightly and on demand, not on pushes or pull requests, so this hook is where a change is checked first.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
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/",
@@ -55,7 +55,9 @@
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",
@@ -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,
@@ -29,7 +29,8 @@ import { capabilityNoteLines } from '../run/readiness.js';
29
29
  import { readBridgeConfig } from "../run/drivers/stdio.js";
30
30
  import { WEBDRIVER_NAMES, readDriverConfig } from '../run/drivers/webdriver.js';
31
31
  import { BROWSER_FIX, automationChecks, probeBrowser, browserFixFor, playwrightVersion } from './check.js';
32
- import { runPersona } from '../run/personaLoop.js';
32
+ import { runPersona, MIN_SESSION_ACTIONS } from '../run/personaLoop.js';
33
+ import { playedToBudget } from '../run/intent.js';
33
34
  import { runModelBudgetUsd } from '../run/budgetReserve.js';
34
35
  import { missingScopeMessage, missingScopes } from '../auth/scopes.js';
35
36
  import { tracesWanted } from '../run/acceptance.js';
@@ -40,6 +41,7 @@ import { bold } from '../ui/index.js';
40
41
  import { reconcileDroppedFindings } from '../run/dropped.js';
41
42
  import * as stateFile from '../run/state.js';
42
43
  import { emitRunEvents } from '../run/synthetic.js';
44
+ import { ingestOriginsFor, playtestTagLine } from '../run/sdkSession.js';
43
45
  import { serveBuildDir } from '../run/serveBuild.js';
44
46
  import { stepLogSetting, stepLogUploadsLine } from '../config.js';
45
47
  import { readLiveSite } from '../run/livesite/options.js';
@@ -818,7 +820,7 @@ export async function playJob({
818
820
  log(`job ${jobId} ${settledState || 'finished'}: refunded ${formatCents(finished.refunded_cents)}.`);
819
821
  // Each thin run, with what it was charged now the job has settled.
820
822
  for (const thin of Array.isArray(finished.thin_runs) ? finished.thin_runs : []) {
821
- const lines = thinRunLines(thin);
823
+ const lines = thinRunLines(thin, { played: Boolean(results.find(result => result && result.runId === thin.run_id)?.playedToBudget) });
822
824
  if (lines.length > 0) log(`run ${thin.run_id}${thin.persona ? ` (${thin.persona})` : ''}: ${lines.join(' ')}`);
823
825
  }
824
826
  }
@@ -844,7 +846,15 @@ export async function playJob({
844
846
  if (playBudgetHit) return EXIT.BUDGET;
845
847
  // The server's settlement is the verdict on the job. A job it settled as
846
848
  // failed (every run refunded, nothing kept) exited 0 in 0.5.0, so a script
847
- // could not tell it from a success.
849
+ // could not tell it from a success. A run that played and wrote its report
850
+ // is a playtest that ran, found something or not (owner, 2026-11-20): the
851
+ // paid local run of that day played 39 actions, wrote a checked report with
852
+ // no finding, was refunded as a thin run, and exited 1.
853
+ const playedThrough = results.filter(result => result && result.playedThrough);
854
+ if (settledState === 'failed' && playedThrough.length > 0) {
855
+ log(`job ${jobId}: the server settled it as failed, but ${playedThrough.length === 1 ? `run ${playedThrough[0].runId} played ${playedThrough[0].actionsTaken} actions and wrote its report` : `${playedThrough.length} runs played and wrote their reports`}, so this exits 0.`);
856
+ return EXIT.OK;
857
+ }
848
858
  if (settledState === 'failed' || settledState === 'stalled') return EXIT.FAILED;
849
859
  return anySucceeded || reportBudgetDelivered ? EXIT.OK : EXIT.FAILED;
850
860
  }
@@ -892,7 +902,7 @@ export async function playPersonaRun({
892
902
  const runTarget = entry.target || target;
893
903
  let driver;
894
904
  try {
895
- 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 }));
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 }));
896
906
  } catch (error) {
897
907
  // A driver that cannot even be built (the browser package missing, say) is
898
908
  // what a new machine hits first. The run is completed as failed now, with
@@ -978,7 +988,7 @@ export async function playPersonaRun({
978
988
  edgePass: options.noEdgePass !== true,
979
989
  replayFindings: options.noReplay !== true,
980
990
  // A web run's findings are replayed in a second browser of the same kind, on the same target, with no recording.
981
- ...(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 })) } : {}),
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 })) } : {}),
982
992
  // A run sold by the minute stops on the clock (../run/playClock.js).
983
993
  playClock: playClockFor(options, entry),
984
994
  ...(options.phone === true && driverName === 'playwright_web' ? { viewport: PHONE_VIEWPORT } : {}),
@@ -1114,14 +1124,19 @@ export async function playPersonaRun({
1114
1124
  ingestKey: (config && config.ingest_key) || process.env.RAVENSIGHT_INGEST_KEY || null,
1115
1125
  playtestToken: entry.playtest_token,
1116
1126
  // The web driver injects the playtest token into the page (see
1117
- // driverOptions), so the game's own SDK sends with it.
1127
+ // driverOptions), so the game's own SDK is the run's telemetry; whether
1128
+ // it carried the tag is said only from the session requests the run saw.
1118
1129
  pageSdk: driverName === 'playwright_web' && Boolean(entry.playtest_token),
1130
+ pageTag: outcome.playtestTag || null,
1119
1131
  context: { jobId, runId, persona: persona.slug, gameVersion: (config && config.game_version) || 'unknown' },
1120
1132
  report: outcome.report,
1121
1133
  driver: driverName,
1122
1134
  log: message => log(`run ${runId}: ${message}`)
1123
1135
  });
1124
1136
  if (emitted.reason) log(`run ${runId}: ${emitted.reason}`);
1137
+ // 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.
1138
+ const tag = outcome.playtestTag;
1139
+ if (!emitted.pageSdk && tag && (tag.state === 'untagged' || tag.state === 'unseen')) log(`run ${runId}: ${playtestTagLine(tag)}`);
1125
1140
  }
1126
1141
 
1127
1142
  // Out of budget while playing, but past the proof bar with its report kept:
@@ -1134,7 +1149,25 @@ export async function playPersonaRun({
1134
1149
  }
1135
1150
 
1136
1151
  log(`run ${runId} (${persona.slug}) ${outcome.state}: ${outcome.actionsTaken} actions, ${outcome.quitReason}.`);
1137
- return { runId, persona: persona.slug, state: outcome.state, quitReason: outcome.quitReason };
1152
+ return { runId, persona: persona.slug, state: outcome.state, quitReason: outcome.quitReason, ...playedFacts(outcome, maxActions) };
1153
+ }
1154
+
1155
+ /**
1156
+ * What the job's exit code and its thin run lines need of a run: how many actions it took, whether it played (at least the
1157
+ * proof bar of actions, or every action it had, and a report written that is not partial) and whether it played to its budget.
1158
+ *
1159
+ * @param {Object} outcome
1160
+ * @param {number} maxActions
1161
+ * @returns {{actionsTaken: number, playedThrough: boolean, playedToBudget: boolean}}
1162
+ */
1163
+ export function playedFacts(outcome, maxActions) {
1164
+ const actionsTaken = Number(outcome && outcome.actionsTaken) || 0;
1165
+ const bar = Math.min(MIN_SESSION_ACTIONS, Number(maxActions) || MIN_SESSION_ACTIONS);
1166
+ return {
1167
+ actionsTaken,
1168
+ playedThrough: Boolean(outcome && outcome.state === 'succeeded' && outcome.report && !outcome.report.partial && actionsTaken >= bar),
1169
+ playedToBudget: Boolean(playedToBudget({ quitReason: outcome && outcome.quitReason, actionsTaken, maxActions }))
1170
+ };
1138
1171
  }
1139
1172
 
1140
1173
  /**
@@ -1304,10 +1337,12 @@ export async function deliver({ deps, api, gameId, jobId, runId, directory, outc
1304
1337
  }
1305
1338
  // A thin run: the server says why it was short, what to try next and how
1306
1339
  // it is billed. Said here and written into report.md, in its words.
1307
- const thin = thinRunLines(answer && answer.run && answer.run.thin_run);
1340
+ // A run that played to its budget is never said to have stopped early (./thinRun.js playedWhy).
1341
+ const played = Boolean(playedToBudget({ quitReason: outcome.quitReason, actionsTaken: outcome.actionsTaken, maxActions: outcome.maxActions }));
1342
+ const thin = thinRunLines(answer && answer.run && answer.run.thin_run, { played });
1308
1343
  if (thin.length > 0) {
1309
1344
  log(`run ${runId}: ${thin.join(' ')}`);
1310
- await writeThinRunSection(directory, answer.run.thin_run);
1345
+ await writeThinRunSection(directory, answer.run.thin_run, { played });
1311
1346
  }
1312
1347
  // What the game's memory made of the notes this run handed on (the server's answer, only when they were sent).
1313
1348
  const remembered = answer && answer.game_memory;
@@ -1787,7 +1822,7 @@ export async function resolveSetup(deps, options, log) {
1787
1822
  *
1788
1823
  * @returns {Object}
1789
1824
  */
1790
- export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null }) {
1825
+ export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null }) {
1791
1826
  // Only the browser driver sends key chords with a modifier.
1792
1827
  const modifier = driverName === 'playwright_web' ? resolveKeyModifier(keyModifier).modifier : null;
1793
1828
  const godot = driverName === 'godot_driver'
@@ -1806,6 +1841,8 @@ export function driverOptions({ headless, driverName, target, directory, entry,
1806
1841
  ...(driverName === 'playwright_web' && phone === true ? { touch: true } : {}),
1807
1842
  // A live URL run (../run/livesite/): its network rules, sign-in and masking.
1808
1843
  ...(driverName === 'playwright_web' && liveSite ? { liveSite } : {}),
1844
+ // 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
+ ...(driverName === 'playwright_web' && apiUrl ? { ingestOrigins: ingestOriginsFor(apiUrl) } : {}),
1809
1846
  ...godot,
1810
1847
  playtest: {
1811
1848
  token: entry.playtest_token || null,
@@ -802,7 +802,8 @@ export function inCharacterSection(markdown) {
802
802
  if (start === -1) return null;
803
803
  const rest = lines.slice(start + 1);
804
804
  const end = rest.findIndex(line => /^#{1,2}\s/.test(line));
805
- const text = (end === -1 ? rest : rest.slice(0, end)).join('\n').trim();
805
+ // The runner's own line under it (./intent.js holdInCharacter: what the record shows instead) is not the persona's voice.
806
+ const text = (end === -1 ? rest : rest.slice(0, end)).filter(line => !line.startsWith('Held to the run\'s record (written by the runner)')).join('\n').trim();
806
807
  if (!text) return null;
807
808
  return { text, fromLog: /written from the run log/i.test(lines[start]) };
808
809
  }
@@ -8,7 +8,7 @@
8
8
  "sound": "8be235bda7903856cd9b1cdb5aad1c327c10af8d86c3b0dbb575f2d323999bb3",
9
9
  "gamenotes": "d137c0951de6fa92de973b7b3e0c5db5193697bdb9b38d4c6281b1fdd63ace53",
10
10
  "claimwords": "7571269538c4683b313bd02117023d9a4971d0956aaa3f2a7ede853357dc819d",
11
- "events": "4f6448051aedcbcd0a5a71dcc11e5529a2b207f73626e88a9e65ab851f10534d",
12
- "eventclaims": "fc1ebc302bb2c4edf7e3790bd5a3a6f970330430a62cf1c6235dc7d39c64666e"
11
+ "events": "4f6be350898693878ec989b9a709e362cc7f2e8b78e4dca48cea76110da6ad0c",
12
+ "eventclaims": "24fdd77b4d4a61da8b5088c97862dcea8b27b871a0c2f2d4d69469de6393d98e"
13
13
  }
14
14
  }
@@ -68,6 +68,15 @@ export function repeatsClaim(sentence, claim, { loose = false } = {}) {
68
68
  return (title >= 1 && shared >= 5) || (title >= 2 && shared >= 4);
69
69
  }
70
70
 
71
+ /**
72
+ * Whether a sentence repeats one turned-away claim (an entry of the claim judge's `turnedAway`, with its `finding`), by the
73
+ * same words as the sweep below. The in-character section is held to it only for a claim the frames contradicted (./intent.js).
74
+ */
75
+ export function repeatsTurnedAway(sentence, entry) {
76
+ if (!entry) return false;
77
+ return repeatsClaim(sentence, { id: entry.finding ? entry.finding.id : entry.id, words: wordsOf(entry.finding || entry) });
78
+ }
79
+
71
80
  /** The sections of report.md a turned-away claim is swept out of. The in-character section is the playtester's own voice and stays. */
72
81
  const SWEPT = /^##\s+(?:What worked|Top issues|What this run didn't cover|Persona summary|Evidence)\b/i;
73
82
  const NEXT_STEP = /^##\s+Suggested next step\b/i;
@@ -1,9 +1,27 @@
1
1
  import path from 'node:path';
2
2
  import { lstat, readdir, realpath, readlink } from 'node:fs/promises';
3
- import { createReadStream } from 'node:fs';
3
+ import { createReadStream, realpathSync } from 'node:fs';
4
4
  import { createHash } from 'node:crypto';
5
5
 
6
6
  export const MOBILE_DRIVERS = Object.freeze(['android_driver', 'ios_driver']);
7
+ function insideRoot(root, file) { return file === root || file.startsWith(root + path.sep); }
8
+ function realOrAncestor(file) {
9
+ let current = file; const tail = [];
10
+ for (;;) {
11
+ try { return path.join(realpathSync(current), ...tail.reverse()); } catch (error) {
12
+ const parent = path.dirname(current);
13
+ if (parent === current) return file;
14
+ tail.push(path.basename(current)); current = parent;
15
+ }
16
+ }
17
+ }
18
+ function configBuild(repoRoot, ref) {
19
+ const resolved = path.resolve(repoRoot, ref);
20
+ if (!insideRoot(path.resolve(repoRoot), resolved) || !insideRoot(realOrAncestor(path.resolve(repoRoot)), realOrAncestor(resolved))) {
21
+ throw new Error('The native build in the project settings must be inside the project folder.');
22
+ }
23
+ return resolved;
24
+ }
7
25
  export function nativeTarget(options = {}, config = null, driverName = options.driver || config?.driver, repoRoot = process.cwd()) {
8
26
  const explicitNative = options.nativeBuild !== undefined;
9
27
  const nativeFlags = ['device', 'package', 'bundleId'].some(key => options[key] !== undefined) || options.portrait === true || options.landscape === true;
@@ -19,10 +37,11 @@ export function nativeTarget(options = {}, config = null, driverName = options.d
19
37
  if (options.portrait && options.landscape) throw new Error('Choose --portrait or --landscape, not both.');
20
38
  if (driverName === 'android_driver' && options.bundleId !== undefined) throw new Error('--bundle-id is for ios_driver; Android uses --package.');
21
39
  if (driverName === 'ios_driver' && options.package !== undefined) throw new Error('--package is for android_driver; iOS uses --bundle-id.');
22
- const build = options.nativeBuild || (config?.build?.kind === 'native_build' ? config.build.ref : null);
40
+ const configRef = config?.build?.kind === 'native_build' ? config.build.ref : null;
41
+ const build = options.nativeBuild || configRef;
23
42
  const native = config?.native && typeof config.native === 'object' ? config.native : {};
24
43
  return {
25
- mode: 'native', driver: driverName, build: build ? path.resolve(repoRoot, build) : null,
44
+ mode: 'native', driver: driverName, build: !build ? null : options.nativeBuild ? path.resolve(repoRoot, build) : configBuild(repoRoot, build),
26
45
  device: options.device || native.device || null,
27
46
  package: options.package || native.package || null, bundleId: options.bundleId || native.bundleId || null,
28
47
  orientation: options.landscape ? 'landscape' : options.portrait ? 'portrait' : native.orientation || 'portrait'
@@ -3,7 +3,7 @@ import { pngFingerprint, screenDelta, significant } from '../pixels.js';
3
3
  import { findRegions } from '../regions.js';
4
4
  import { createMarker, isMarkTarget, marksFor, marksText, resolveMark } from '../marks.js';
5
5
  import { gameTime, timeFreezeInit } from '../timeFreeze.js';
6
- import { createSdkSessions, sdkSessionAnswer } from '../sdkSession.js';
6
+ import { createSdkSessions, ingestOriginsFor, recordSessionAnswer } from '../sdkSession.js';
7
7
  import { STRIP_MIN_MS, stripNote, stripTimes, stripTokens } from '../strip.js';
8
8
  import { GAMEPAD_BUTTONS, gamepadState, virtualGamepadInit } from '../gamepad.js';
9
9
  // any-game hook: sound as measured evidence (../anygame/sound.js).
@@ -1107,6 +1107,18 @@ export function textOnScreen(nodes, target) {
1107
1107
  /** What a target that is none of a ref, coordinates or visible text is told. */
1108
1108
  export const NOT_A_TARGET_MESSAGE = 'is not a ref, coordinates or text on the current screen; use the ref the snapshot shows, such as e12';
1109
1109
 
1110
+ /**
1111
+ * How long a click by words on a canvas game looks for those words in the page before it is refused. The words of a game drawn
1112
+ * on a canvas are in the picture, not in the page, so there is nothing to wait for: the paid local run of 2026-11-20 waited the
1113
+ * full action timeout (15 s) on each of four such clicks, about a fifth of its play.
1114
+ */
1115
+ export const CANVAS_TEXT_CHECK_MS = 400;
1116
+
1117
+ /** What a click by words that a canvas game only draws is told: where to click instead. */
1118
+ export function canvasTextMessage(target) {
1119
+ return `${JSON.stringify(String(target).trim())} is drawn on the game's canvas, not written in the page, so it cannot be clicked by its words. Click where the picture shows it instead: its grid cell (such as C3), its mark (such as m2), or x and y read off the screenshot. This is a limit of the runner, not of the game`;
1120
+ }
1121
+
1110
1122
  /**
1111
1123
  * A locator narrowed to visible elements when this Playwright can: a mobile
1112
1124
  * only duplicate hidden by CSS must never be the one clicked.
@@ -1432,7 +1444,7 @@ export async function needsFrame(page, text) {
1432
1444
  try { return (await page.evaluate(pageHasLargeCanvas, LARGE_CANVAS_SHARE)) === true; } catch { return false; }
1433
1445
  }
1434
1446
 
1435
- export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null } = {}) {
1447
+ export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null, ingestOrigins = null } = {}) {
1436
1448
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1437
1449
  // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
1438
1450
  let avoidGuard = createAvoidGuard([]);
@@ -1444,6 +1456,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1444
1456
  // The game's own SDK opening its session: each answer, so a refusal that leaves the run with no game events is said plainly (../sdkSession.js).
1445
1457
  const sdkSessions = createSdkSessions();
1446
1458
  const sdkSessionReads = new Set();
1459
+ // Only a POST to one of these origins is the game's Ravensight session; the game's own backend at the same path is not.
1460
+ const sessionOrigins = Array.isArray(ingestOrigins) && ingestOrigins.length > 0 ? ingestOrigins : ingestOriginsFor();
1447
1461
  let target = null;
1448
1462
  let runDirectory = null;
1449
1463
  let videoRequested = false;
@@ -1805,7 +1819,21 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1805
1819
  throw new TargetError(`${JSON.stringify(target)} ${NOT_A_TARGET_MESSAGE}`);
1806
1820
  }
1807
1821
  }
1808
- return resolveLocator(current, target);
1822
+ const locator = resolveLocator(current, target);
1823
+ // A game drawn on a canvas: words the page does not hold are in the picture, so the click is refused at once, with where to
1824
+ // click instead, rather than searched for until the action timeout. Words the page does hold (a button around the canvas) click.
1825
+ if (canvasPlay && !(await inPageNow(locator))) throw new TargetError(canvasTextMessage(target));
1826
+ return locator;
1827
+ }
1828
+
1829
+ /** Whether a locator matches anything in the page right now, asked once and never waited for. */
1830
+ async function inPageNow(locator) {
1831
+ if (!locator || typeof locator.count !== 'function') return true;
1832
+ try {
1833
+ return (await withTimeout(Promise.resolve(locator.count()), CANVAS_TEXT_CHECK_MS)) > 0;
1834
+ } catch {
1835
+ return false;
1836
+ }
1809
1837
  }
1810
1838
 
1811
1839
  /**
@@ -2937,10 +2965,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2937
2965
  if (typeof context.addInitScript === 'function') await context.addInitScript(capabilitySignalsInit);
2938
2966
  // The game's own SDK events: its track calls are read as they leave the page, never held, changed or answered here.
2939
2967
  if (typeof context.on === 'function') context.on('request', request => tapSdkEvents(request, gameEvents));
2940
- // And the answer to its session request, read only: the status, the key's kind, the error code; never the key or the token.
2968
+ // And the answer to its session request, read only: the status, the key's kind, the error code, and whether it carried
2969
+ // this run's own token (matched in constant time, ../sdkSession.js); never the key or the token. A session open it
2970
+ // cannot read, including a read that fails, is counted as unreadable rather than dropped.
2941
2971
  if (typeof context.on === 'function') {
2942
2972
  context.on('response', response => {
2943
- const read = sdkSessionAnswer(response).then(answer => sdkSessions.record(answer), () => {});
2973
+ const read = recordSessionAnswer(sdkSessions, response, { token: playtest && playtest.token ? playtest.token : null, origins: sessionOrigins });
2944
2974
  sdkSessionReads.add(read);
2945
2975
  read.finally(() => sdkSessionReads.delete(read));
2946
2976
  });
@@ -3332,11 +3362,14 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3332
3362
  */
3333
3363
  /** The game's own SDK events this run (../events.js): marked at each input, flushed before the page closes, read by the report. */
3334
3364
  gameEvents,
3335
- /** The game's own SDK's session answers: how many opened, and each refusal (../sdkSession.js). */
3365
+ /**
3366
+ * The game's own SDK's session answers: how many opened, how many of those without the run's playtest tag, the SDK
3367
+ * names seen, each refusal, and whether the page was handed a tag at all (../sdkSession.js).
3368
+ */
3336
3369
  async sdkSessions() {
3337
3370
  // An answer still being read (its body) is waited for, briefly, so a refusal at the end of play is not missed.
3338
3371
  if (sdkSessionReads.size > 0) await Promise.race([Promise.allSettled([...sdkSessionReads]), new Promise(resolve => setTimeout(resolve, 2000))]);
3339
- return sdkSessions.summary();
3372
+ return { ...sdkSessions.summary(), given: Boolean(playtest && playtest.token) };
3340
3373
  },
3341
3374
  /** Mark the page clock just before input `step` (or 'end' after play), so each event is placed at the step it happened. */
3342
3375
  async markGameEvents(step) {
@@ -133,7 +133,10 @@ function valueKey(e, about) {
133
133
 
134
134
  const propsText = props => Object.entries(props).map(([k, v]) => `${k}=${v}`).join(' ');
135
135
  const show = e => `${e.name}${Object.keys(e.props).length ? ` (${propsText(e.props).slice(0, 80)})` : ''}`;
136
- const atStep = e => (e.phase === 'play' && Number.isSafeInteger(e.step) ? ` at step ${e.step}` : '');
136
+ // An event whose timestamp was a whole second is placed at the latest step of that second, with `from` its earliest (lib/events.mjs):
137
+ // it is inside a claim's steps only when all of its steps are, so an event that may have come before the claim's inputs never answers it.
138
+ const earliest = e => (e.from === 'before' ? -1 : Number.isSafeInteger(e.from) ? e.from : e.step);
139
+ const atStep = e => (e.phase === 'play' && Number.isSafeInteger(e.step) ? (Number.isSafeInteger(e.from) ? ` at steps ${e.from} to ${e.step}` : e.from === 'before' ? ` before the first input or at step ${e.step}` : ` at step ${e.step}`) : '');
137
140
 
138
141
  /** The steps a claim is about: the inputs since the playtester last looked (or a test's own inputs), or the few before it. */
139
142
  function windowOf(claim) {
@@ -162,7 +165,7 @@ export function eventsVerdict(run, claim) {
162
165
  const win = windowOf(claim);
163
166
  if (!win) return null;
164
167
  const title = String(claim.title || '');
165
- const inWin = evs.filter(e => e.phase === 'play' && Number.isSafeInteger(e.step) && e.step >= win.from && e.step <= win.to);
168
+ const inWin = evs.filter(e => e.phase === 'play' && Number.isSafeInteger(e.step) && earliest(e) >= win.from && e.step <= win.to);
166
169
  const done = (verdict, why, list, extra = {}) => {
167
170
  const v = { verdict, why: noDashes(why), events: list.slice(0, 4).map(e => ({ step: e.step, name: e.name, props: e.props })), ...extra };
168
171
  if (!memo.has(run)) memo.set(run, new Map());
@@ -209,7 +212,7 @@ export function eventsVerdict(run, claim) {
209
212
  const keyed = evs.filter(e => e.phase === 'play' && Number.isSafeInteger(e.step) && e.step <= win.to && eventMatches(e, about)).map(e => ({ e, k: valueKey(e, about) })).filter(x => x.k);
210
213
  for (let i = 1; i < keyed.length; i++) {
211
214
  const a = keyed[i - 1], b = keyed[i];
212
- if (b.e.step < win.from || a.k !== b.k) continue;
215
+ if (earliest(b.e) < win.from || a.k !== b.k) continue;
213
216
  const from = a.e.props[a.k], to = b.e.props[b.k];
214
217
  if (from === to) continue;
215
218
  if (about.way === 'any' || (about.way === 'down' ? to < from : to > from)) return done('contradicted', `the game's own events show ${b.k} go from ${from}${atStep(a.e)} to ${to}${atStep(b.e)}`, [a.e, b.e]);
package/src/run/events.js CHANGED
@@ -103,6 +103,11 @@ function timestampOf(raw) {
103
103
  if (t < 1e11) t *= 1000;
104
104
  return Math.floor(t);
105
105
  }
106
+ /**
107
+ * Whether an SDK timestamp is a whole second (the LÖVE SDK's os.time, and the JavaScript SDK before it sent milliseconds): the event
108
+ * happened somewhere in that second, which can span several steps of game time (a key press plays in about 0.65 s of it).
109
+ */
110
+ const wholeSecond = raw => { const t = Number(raw); return Number.isFinite(t) && t > 0 && t < 1e11 && Number.isInteger(t); };
106
111
 
107
112
  /**
108
113
  * The events in one track request body, as the SDKs send them: `{ events: [...] }`
@@ -127,7 +132,7 @@ export function parseTrackBody(body, headers = {}) {
127
132
  if (!name) continue;
128
133
  // The SDK's own id for an event, when it sends one: a retry carries the same id.
129
134
  const id = typeof e.data?.rs_event_id === 'string' ? e.data.rs_event_id.slice(0, 64) : null;
130
- out.push({ name, props: cleanProps(e.data ?? e.properties ?? e.props), ts: timestampOf(e.timestamp), ...(id ? { id } : {}) });
135
+ out.push({ name, props: cleanProps(e.data ?? e.properties ?? e.props), ts: timestampOf(e.timestamp), ...(wholeSecond(e.timestamp) ? { coarse: true } : {}), ...(id ? { id } : {}) });
131
136
  }
132
137
  return out;
133
138
  } catch {
@@ -183,9 +188,11 @@ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {})
183
188
  }
184
189
 
185
190
  /**
186
- * Where an event belongs: `{ phase: 'before' | 'play' | 'after', step, by }`.
191
+ * Where an event belongs: `{ phase: 'before' | 'play' | 'after', step, by, from? }`.
187
192
  * By its own timestamp against the page clock marks when it can be (`by:
188
193
  * 'clock'`); by when it reached the runner otherwise (`by: 'arrival'`).
194
+ * `from` is the earliest step a whole-second timestamp can belong to ('before'
195
+ * the first input, or a step) when that is not `step`.
189
196
  */
190
197
  function place(e) {
191
198
  const timed = marks.filter(m => m.pageMs !== null);
@@ -193,10 +200,22 @@ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {})
193
200
  const first = timed[0], last = timed.at(-1);
194
201
  // A clock that is not the page's own (an engine that keeps its own) is read by arrival instead.
195
202
  const sane = e.ts >= first.pageMs - 10 * 60 * 1000 && e.ts <= last.pageMs + Math.max(0, now() - last.realAt) + 2 * 60 * 1000;
196
- if (sane) return at(timed, m => m.pageMs <= e.ts, 'clock');
203
+ if (sane && !e.coarse) return at(timed, m => m.pageMs <= e.ts, 'clock');
204
+ // A whole-second stamp happened somewhere in its second. Placed by the second's start, the paid run of 2026-11-20 (f408c47) put
205
+ // every Wish You Were Hired event one to three steps before the input that sent it. It is placed at the latest step of its second,
206
+ // never after the step it reached the runner by, and `from` says how early it may be.
207
+ if (sane) {
208
+ const lo = at(timed, m => m.pageMs <= e.ts, 'clock');
209
+ let hi = at(timed, m => m.pageMs <= e.ts + 999, 'clock');
210
+ const arrived = at(marks, m => m.realAt <= e.arrivedAt, 'clock');
211
+ if (rank(arrived) < rank(hi)) hi = rank(arrived) < rank(lo) ? lo : arrived;
212
+ const from = rank(lo) < rank(hi) ? (lo.phase === 'before' ? 'before' : lo.step) : null;
213
+ return { ...hi, ...(from !== null ? { from } : {}) };
214
+ }
197
215
  }
198
216
  return at(marks, m => m.realAt <= e.arrivedAt, 'arrival');
199
217
  }
218
+ const rank = p => (p.phase === 'before' ? -1 : p.phase === 'after' ? Infinity : p.step);
200
219
  const at = (list, before, by) => {
201
220
  let found = null;
202
221
  for (const m of list) if (before(m)) found = m;
@@ -247,13 +266,20 @@ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {})
247
266
  const by = placed.reduce((o, e) => { o[e.by] = (o[e.by] || 0) + 1; return o; }, {});
248
267
  const names = {};
249
268
  for (const e of events) names[e.name] = (names[e.name] || 0) + 1;
250
- return { total, kept: events.length, dropped, duplicates, untimed, bodies, clock: by.arrival ? (by.clock ? 'mixed' : 'arrival') : 'clock', names, marks: marks.length, events: placed };
269
+ // `coarse`: events whose timestamp was a whole second, each placed across the steps of that second (`from` to `step`).
270
+ return { total, kept: events.length, dropped, duplicates, untimed, coarse: events.filter(e => e.coarse).length, bodies, clock: by.arrival ? (by.clock ? 'mixed' : 'arrival') : 'clock', names, marks: marks.length, events: placed };
251
271
  }
252
272
 
253
273
  return { tap, mark, markPage, flush, pendingForPlan, planned, record, get size() { return events.length; } };
254
274
  }
255
275
 
256
- const stepWords = e => (e.phase === 'before' ? 'before the first input' : e.phase === 'after' ? 'after play' : `step ${e.step}`);
276
+ /** Where an event was placed, in words: a step, or the steps a whole-second timestamp spans. */
277
+ const stepWords = e => {
278
+ if (e.phase === 'before') return 'before the first input';
279
+ if (e.phase === 'after') return Number.isSafeInteger(e.from) ? `at step ${e.from} or after play` : 'after play';
280
+ if (e.from === 'before') return `before the first input or at step ${e.step}`;
281
+ return Number.isSafeInteger(e.from) ? `steps ${e.from} to ${e.step}` : `step ${e.step}`;
282
+ };
257
283
 
258
284
  /**
259
285
  * Events as short lines for the planner: each kind of event on one line, in
@@ -327,7 +353,7 @@ export function eventsReportLines(run, { findings = [], turnedAway = [] } = {})
327
353
  return md;
328
354
  }
329
355
  const names = Object.entries(g.names).sort((a, b) => b[1] - a[1]);
330
- md.push(`The game sent ${g.total} analytics event${g.total === 1 ? '' : 's'} through its own Ravensight SDK during this run (${names.slice(0, 8).map(([n, c]) => `${n} ${c}`).join(', ')}${names.length > 8 ? `, and ${names.length - 8} more kinds` : ''}). The runner read them as the game sent them, so they are measured, not judged from the picture. ${g.clock === 'clock' ? 'Each is placed at the step its own timestamp falls in.' : 'Some carried no usable timestamp, so they are placed at the step they reached the runner, which can be a few steps late.'}${g.dropped ? ` ${g.dropped} more were counted and not kept.` : ''}`);
356
+ md.push(`The game sent ${g.total} analytics event${g.total === 1 ? '' : 's'} through its own Ravensight SDK during this run (${names.slice(0, 8).map(([n, c]) => `${n} ${c}`).join(', ')}${names.length > 8 ? `, and ${names.length - 8} more kinds` : ''}). The runner read them as the game sent them, so they are measured, not judged from the picture. ${g.clock === 'clock' ? 'Each is placed at the step its own timestamp falls in.' : 'Some carried no usable timestamp, so they are placed at the step they reached the runner, which can be a few steps late.'}${g.coarse ? ` ${g.coarse === g.kept ? 'Their timestamps are' : `${g.coarse} of them carry timestamps`} in whole seconds, so ${g.coarse === 1 ? 'it is' : 'each is'} placed across the steps of that second.` : ''}${g.dropped ? ` ${g.dropped} more were counted and not kept.` : ''}`);
331
357
  md.push('');
332
358
  const decided = eventsDecided(run);
333
359
  const confirmed = (findings || []).filter(f => decided.get(f.title)?.verdict === 'confirmed');
@@ -350,5 +376,5 @@ export function eventsUsage(run) {
350
376
  const g = run?.gameEvents;
351
377
  if (!g) return null;
352
378
  const decided = [...eventsDecided(run).entries()].map(([title, v]) => ({ title: cleanText(title, 120), verdict: v.verdict, why: v.why, ...(v.fault !== undefined ? { fault: v.fault } : {}) }));
353
- return { total: g.total, kept: g.kept, dropped: g.dropped, duplicates: g.duplicates, untimed: g.untimed, clock: g.clock, names: g.names, decided, events: g.events.slice(0, EVENT_LIMITS.usageEvents).map(e => ({ step: e.step, phase: e.phase, name: e.name, props: e.props })) };
379
+ return { total: g.total, kept: g.kept, dropped: g.dropped, duplicates: g.duplicates, untimed: g.untimed, ...(g.coarse ? { coarse: g.coarse } : {}), clock: g.clock, names: g.names, decided, events: g.events.slice(0, EVENT_LIMITS.usageEvents).map(e => ({ step: e.step, ...(e.from !== undefined ? { from: e.from } : {}), phase: e.phase, name: e.name, props: e.props })) };
354
380
  }