ravensight-playtest 0.8.3 → 0.10.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 (66) hide show
  1. package/README.md +280 -66
  2. package/addons/ravensight_driver/driver.gd +666 -21
  3. package/docs/ADAPTERS.md +11 -7
  4. package/docs/NATIVE_RUNNER.md +3 -1
  5. package/docs/godot-driver.md +127 -13
  6. package/package.json +8 -6
  7. package/src/api/client.js +4 -3
  8. package/src/cli.js +84 -25
  9. package/src/commands/check.js +30 -4
  10. package/src/commands/fakeCore.js +1 -0
  11. package/src/commands/hosted.js +41 -12
  12. package/src/commands/init.js +17 -1
  13. package/src/commands/run.js +209 -14
  14. package/src/commands/upload.js +6 -2
  15. package/src/commands/validate.js +1 -1
  16. package/src/commands/validateHosted.js +50 -5
  17. package/src/config.js +33 -2
  18. package/src/hosted/archivePreflight.js +7 -7
  19. package/src/hosted/buildUpload.js +89 -8
  20. package/src/hosted/recordedRun.js +141 -26
  21. package/src/hosted/status.js +19 -10
  22. package/src/run/actionSelector.js +14 -3
  23. package/src/run/aggregate.js +57 -3
  24. package/src/run/anygame/controlbook.js +179 -0
  25. package/src/run/anygame/genre.js +179 -0
  26. package/src/run/anygame/index.js +258 -0
  27. package/src/run/anygame/language.js +336 -0
  28. package/src/run/anygame/memory.js +330 -0
  29. package/src/run/anygame/shared-hashes.json +10 -0
  30. package/src/run/anygame/shared.js +24 -0
  31. package/src/run/anygame/sound.js +342 -0
  32. package/src/run/args.js +75 -8
  33. package/src/run/choiceCheck.js +312 -0
  34. package/src/run/context.js +254 -13
  35. package/src/run/drivers/godot-observation.js +93 -6
  36. package/src/run/drivers/godot.js +769 -46
  37. package/src/run/drivers/recording.js +24 -4
  38. package/src/run/drivers/web.js +1242 -77
  39. package/src/run/edgePass.js +731 -0
  40. package/src/run/fixLoop.js +5 -4
  41. package/src/run/focus.js +65 -0
  42. package/src/run/gamepad.js +108 -0
  43. package/src/run/godotEdgePass.js +235 -0
  44. package/src/run/godotTesterProbes.js +192 -0
  45. package/src/run/headings.js +21 -0
  46. package/src/run/honesty.js +544 -0
  47. package/src/run/inputs.js +256 -0
  48. package/src/run/marks.js +142 -0
  49. package/src/run/personaLoop.js +1000 -79
  50. package/src/run/phone.js +7 -0
  51. package/src/run/pixels.js +215 -0
  52. package/src/run/playClock.js +162 -0
  53. package/src/run/readiness.js +585 -0
  54. package/src/run/refusal.js +67 -0
  55. package/src/run/regions.js +119 -0
  56. package/src/run/report.js +14 -2
  57. package/src/run/reportChecks.js +472 -0
  58. package/src/run/resume.js +3 -2
  59. package/src/run/screenshots.js +161 -0
  60. package/src/run/strip.js +114 -0
  61. package/src/run/testerLedger.js +312 -0
  62. package/src/run/testerProbes.js +584 -0
  63. package/src/run/thinRun.js +102 -0
  64. package/src/run/timeFreeze.js +79 -0
  65. package/src/run/tools.js +454 -29
  66. package/src/runDefaults.js +24 -2
@@ -0,0 +1,161 @@
1
+ import { readFile, unlink } from 'node:fs/promises';
2
+ import { createDistinct, pngFingerprint, sameScreen, screenDelta } from './pixels.js';
3
+
4
+ /**
5
+ * A screen is a new scene when at least this share of it differs from every
6
+ * scene seen so far: a new menu, a map, a dialog over the map. A counter that
7
+ * ticked or a row that was added is the same scene. The cloud runner's figure
8
+ * for "the same screen" is 0.15; a dialog that covers a sixth of the screen
9
+ * is worth a picture, so this is a little under it.
10
+ */
11
+ export const SCENE_SHARE = 0.12;
12
+
13
+ /**
14
+ * The names of the controls a screen's text shows: the quoted text on every
15
+ * line that is a pressable thing, in either driver's wording (a Godot
16
+ * outline's `Button EndTurn "End Turn"`, a web snapshot's `- button "Start"`).
17
+ *
18
+ * Two menus on one dark background are the same picture by area and a
19
+ * different screen by what can be pressed on them, which is how a Council
20
+ * screen and a Diplomacy screen went unsaved beside a title screen.
21
+ *
22
+ * @param {string} text
23
+ * @returns {Set<string>}
24
+ */
25
+ export function controlWords(text) {
26
+ const words = new Set();
27
+ for (const line of String(text == null ? '' : text).split('\n')) {
28
+ if (!/^\s*(?:- (?:button|link|checkbox|radio|tab|menuitem|option|combobox|textbox|switch)\b|\w*(?:Button|LineEdit|CheckBox|OptionButton|TextEdit)\b)/.test(line)) continue;
29
+ const match = line.match(/"((?:[^"\\]|\\.){1,120})"/);
30
+ if (match) words.add(match[1]);
31
+ }
32
+ return words;
33
+ }
34
+
35
+ /** Fewer named controls than this say too little to tell two screens apart. */
36
+ export const MIN_CONTROL_WORDS = 2;
37
+
38
+ /** Two screens share this much of their controls, or they are different screens. */
39
+ export const SAME_CONTROLS_SHARE = 0.5;
40
+
41
+ /** Whether two sets of control names are one screen's: most of the larger set is in the other. */
42
+ export function sameControls(a, b) {
43
+ if (a.size < MIN_CONTROL_WORDS || b.size < MIN_CONTROL_WORDS) return true;
44
+ let shared = 0;
45
+ for (const word of a) if (b.has(word)) shared += 1;
46
+ return shared >= SAME_CONTROLS_SHARE * Math.max(a.size, b.size);
47
+ }
48
+
49
+ /** The most screenshots the runner saves on its own for scenes not seen before. */
50
+ export const MAX_SCENE_SCREENSHOTS = 12;
51
+
52
+ /**
53
+ * One run's saved screenshots, without the same screen twice in a row.
54
+ *
55
+ * A persona asks for a screenshot to look and to keep evidence, and the runner
56
+ * takes its own at the landing, on a console error and at the end. On a screen
57
+ * that has not moved those were the same picture saved again and again: four
58
+ * of thirteen files in one paid run, five of six in another. A new screenshot
59
+ * that shows what the last saved one shows (./pixels.js: identical bytes, or
60
+ * nothing a player would notice, so a blinking cursor is not a new screen) is
61
+ * deleted, and the earlier file stands for both.
62
+ *
63
+ * Only the last saved screenshot is compared. A screen the run came back to
64
+ * later is saved again: it is evidence of where the run was at that point.
65
+ *
66
+ * @param {{read?: Function, remove?: Function}} [io] test seams
67
+ */
68
+ export function createScreenshotKeeper({ read = readFile, remove = unlink } = {}) {
69
+ let last = null;
70
+ const distinct = createDistinct();
71
+ // Every scene seen, as the driver's probe (one size, so they compare).
72
+ const scenes = [];
73
+ let sceneShots = 0;
74
+ const keeper = {
75
+ /**
76
+ * Save a screenshot when the screen is a scene not seen before in this
77
+ * run, so the evidence shows every screen the persona reached and not
78
+ * only the ones it thought to photograph. Free: no model is asked.
79
+ *
80
+ * Needs a driver that can hand over the screen without saving it
81
+ * (`screenProbe`); with none, nothing is saved here.
82
+ *
83
+ * @param {Object} driver
84
+ * @param {string} name
85
+ * @param {{save?: boolean, text?: string}} [options] save false only
86
+ * remembers the scene, for a screen whose picture was just saved another
87
+ * way (the landing); text is the screen's observation text, whose
88
+ * controls tell two look-alike menus apart
89
+ * @returns {Promise<Object|null>} the saved shot, or null when the scene
90
+ * is not new, the limit is reached, or the last saved file already shows it
91
+ */
92
+ async scene(driver, name, { save = true, text = '' } = {}) {
93
+ if (!driver || typeof driver.screenProbe !== 'function') return null;
94
+ let probe = null;
95
+ try {
96
+ probe = pngFingerprint(await driver.screenProbe());
97
+ } catch {
98
+ return null;
99
+ }
100
+ if (!probe) return null;
101
+ const words = controlWords(text);
102
+ // The same scene looks the same and offers the same controls.
103
+ const seen = scenes.some(scene => {
104
+ const delta = screenDelta(scene.probe, probe);
105
+ return delta !== null && delta.area < SCENE_SHARE * probe.width * probe.height && sameControls(scene.words, words);
106
+ });
107
+ if (seen) return null;
108
+ scenes.push({ probe, words });
109
+ if (!save || sceneShots >= MAX_SCENE_SCREENSHOTS) return null;
110
+ const taken = await keeper.take(driver, name);
111
+ if (taken.duplicate || !taken.shot || !taken.shot.relativePath) return null;
112
+ sceneShots += 1;
113
+ return taken.shot;
114
+ },
115
+
116
+ /** How many different scenes the run has been on, or null with no probe. */
117
+ get scenes() {
118
+ return scenes.length > 0 ? scenes.length : null;
119
+ },
120
+
121
+ /**
122
+ * @param {Object} driver
123
+ * @param {string} name
124
+ * @returns {Promise<{shot: Object|null, duplicate: boolean, seen: boolean}>}
125
+ * `shot` is the driver's answer, or the earlier shot when this one was
126
+ * the same screen; `seen` says whether the model was already shown it
127
+ */
128
+ async take(driver, name) {
129
+ const shot = await driver.screenshot(name);
130
+ if (!shot || !shot.relativePath || !shot.path) return { shot: shot || null, duplicate: false, seen: false };
131
+ let bytes = null;
132
+ try {
133
+ bytes = await read(shot.path);
134
+ } catch {
135
+ // A file that cannot be read back is kept and compared with nothing.
136
+ last = null;
137
+ return { shot, duplicate: false, seen: false };
138
+ }
139
+ if (last && sameScreen(last.bytes, bytes)) {
140
+ await remove(shot.path).catch(() => {});
141
+ return { shot: last.shot, duplicate: true, seen: last.seen };
142
+ }
143
+ last = { shot, bytes, seen: false };
144
+ distinct.add(bytes);
145
+ return { shot, duplicate: false, seen: false };
146
+ },
147
+
148
+ /** The model was shown the last saved screenshot. */
149
+ markSeen() {
150
+ if (last) last.seen = true;
151
+ },
152
+
153
+ /** How many different screens the saved screenshots show. */
154
+ get distinctScreens() {
155
+ return distinct.count;
156
+ }
157
+ };
158
+ return keeper;
159
+ }
160
+
161
+ export default createScreenshotKeeper;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The frame strip: what the game looked like WHILE an input played.
3
+ *
4
+ * A persona used to see only the screen an action ended on. A key held for a
5
+ * second and a half is a second and a half of game it never saw, and in a
6
+ * paid run that made a false finding: the runner fell into a gap, went back
7
+ * to the start of the level and ran on because the key was still down, and
8
+ * the persona, shown only where it stopped, reported "respawned at 38 m".
9
+ *
10
+ * So while a held key, a held press, a drag or a timed sequence plays on a
11
+ * game shown as a picture, the driver takes a few small frames at even
12
+ * moments. When they show the game moving, they are drawn in one row under
13
+ * the picture of the screen afterwards: one image, as the step allows, with
14
+ * the big picture's coordinates unchanged. When nothing moved, no strip is
15
+ * sent and the result says so.
16
+ *
17
+ * The cost is the strip's own pixels: a row a quarter of the screen's height,
18
+ * so about a quarter more image tokens on the turns that carry one
19
+ * ({@link stripTokens}).
20
+ */
21
+
22
+ /** An input shorter than this gets no strip: there is nothing between its ends. */
23
+ export const STRIP_MIN_MS = 400;
24
+
25
+ /** The most frames in a strip. */
26
+ export const STRIP_MAX_FRAMES = 4;
27
+
28
+ /** A frame in the strip is this share of the screen's width and height. */
29
+ export const STRIP_SCALE = 0.25;
30
+
31
+ /**
32
+ * How many frames an input of this length gets: two for a short one, up to
33
+ * four for a long one.
34
+ *
35
+ * @param {number} durationMs
36
+ * @returns {number}
37
+ */
38
+ export function stripFrameCount(durationMs) {
39
+ const ms = Number(durationMs) || 0;
40
+ if (ms < STRIP_MIN_MS) return 0;
41
+ if (ms < 800) return 2;
42
+ if (ms < 1600) return 3;
43
+ return STRIP_MAX_FRAMES;
44
+ }
45
+
46
+ /**
47
+ * When the frames are taken, in ms from the start: even moments inside the
48
+ * input, never its two ends (the end is the big picture).
49
+ *
50
+ * @param {number} durationMs
51
+ * @returns {Array<number>}
52
+ */
53
+ export function stripTimes(durationMs) {
54
+ const count = stripFrameCount(durationMs);
55
+ return Array.from({ length: count }, (_, i) => Math.round((Number(durationMs) * (i + 1)) / (count + 1)));
56
+ }
57
+
58
+ /** A time as the strip's caption and the result's words: "0.4 s". */
59
+ export function stripLabel(ms) {
60
+ return `${(Math.round(Number(ms) / 100) / 10).toFixed(1)} s`;
61
+ }
62
+
63
+ /**
64
+ * What the result says about a strip.
65
+ *
66
+ * @param {{times: Array<number>, moved: boolean, endedWhereItBegan?: boolean}} strip
67
+ * @returns {string}
68
+ */
69
+ export function stripNote(strip) {
70
+ if (!strip || !Array.isArray(strip.times) || strip.times.length === 0) return '';
71
+ const labels = strip.times.map(stripLabel).join(', ');
72
+ if (!strip.moved) return `Nothing on the screen moved while this played (looked at ${labels}).`;
73
+ return `The row of small frames under the picture shows the game WHILE this played, left to right at ${labels}; the big picture is the screen after it.${strip.endedWhereItBegan ? ' The screen ended as it began, so what happened in between is only in the small frames.' : ''} Read what happened from the frames in order (a fall, a respawn, a jump that landed short) before you describe it. A key that shows no effect in any frame (a jump key, and the character never leaves the ground) did nothing: say that, and try the other keys the controls name before you judge the game.`;
74
+ }
75
+
76
+ /**
77
+ * The composite's size and what it costs to send, against the plain picture.
78
+ * Image tokens are about width times height over 750.
79
+ *
80
+ * @param {number} width
81
+ * @param {number} height
82
+ * @returns {{width: number, height: number, stripHeight: number, tokens: number, plainTokens: number, extraTokens: number}}
83
+ */
84
+ export function stripTokens(width, height) {
85
+ const stripHeight = Math.round(height * STRIP_SCALE);
86
+ const tokens = Math.round((width * (height + stripHeight)) / 750);
87
+ const plainTokens = Math.round((width * height) / 750);
88
+ return { width, height: height + stripHeight, stripHeight, tokens, plainTokens, extraTokens: tokens - plainTokens };
89
+ }
90
+
91
+ /**
92
+ * The page a browser draws to make the composite: the picture, and under it
93
+ * the frames with their times.
94
+ *
95
+ * @param {{data: Buffer, mediaType: string, width: number, height: number}} frame the picture of the screen afterwards
96
+ * @param {Array<{data: Buffer, mediaType?: string, atMs: number}>} frames
97
+ * @returns {string}
98
+ */
99
+ export function stripHtml(frame, frames) {
100
+ const w = Math.round(frame.width * STRIP_SCALE);
101
+ const h = Math.round(frame.height * STRIP_SCALE);
102
+ const src = (data, mediaType) => `data:${mediaType};base64,${Buffer.from(data).toString('base64')}`;
103
+ const cells = frames.slice(0, STRIP_MAX_FRAMES).map(entry => `<div class="cell"><img src="${src(entry.data, entry.mediaType || 'image/png')}" width="${w}" height="${h}"><span>${stripLabel(entry.atMs)}</span></div>`).join('');
104
+ return `<!doctype html><html><head><style>
105
+ html,body{margin:0;padding:0;background:#111;overflow:hidden}
106
+ .main{display:block;width:${frame.width}px;height:${frame.height}px}
107
+ .row{display:flex;height:${h}px;width:${frame.width}px;background:#111}
108
+ .cell{position:relative;width:${w}px;height:${h}px;box-sizing:border-box;border-left:2px solid #f5c542}
109
+ .cell img{display:block;width:${w}px;height:${h}px}
110
+ .cell span{position:absolute;left:4px;top:3px;font:bold 13px sans-serif;color:#111;background:#f5c542;padding:1px 5px;border-radius:3px}
111
+ </style></head><body><img class="main" src="${src(frame.data, frame.mediaType)}"><div class="row">${cells}</div></body></html>`;
112
+ }
113
+
114
+ export default { stripTimes, stripFrameCount, stripNote, stripLabel, stripTokens, stripHtml, STRIP_MIN_MS, STRIP_MAX_FRAMES, STRIP_SCALE };
@@ -0,0 +1,312 @@
1
+ // Tester techniques for the local loop: what the runner itself can keep
2
+ // track of, and recognise, while a persona plays. No model call, no charge.
3
+ //
4
+ // - a coverage map: the screens the persona was shown, the controls each
5
+ // listed, which of them an input named, and which none ever did;
6
+ // - the game's own numbers breaking their rules (a counter below zero, a
7
+ // value above the maximum printed beside it, a score that falls, a value
8
+ // that is not a number);
9
+ // - placeholder text: a value never set, a template never filled in, a
10
+ // text key never translated.
11
+ //
12
+ // It reads only the text the driver already hands the persona (the page's
13
+ // snapshot, a Godot scene outline, a terminal screen), so it works on every
14
+ // driver that has text and says so where there is none. What it has no record
15
+ // of is "not tested", never "fine". The charter, the probes and trying a bug
16
+ // again are the persona's, through the persona-playtest skill; this module
17
+ // only reports what the runner can stand behind.
18
+ import crypto from 'node:crypto';
19
+ import { runnerFinding, stepsBefore } from './honesty.js';
20
+ import { redactSecrets } from './secretScan.js';
21
+
22
+ /** The heading the ledger's section is written under in report.md. */
23
+ export const TESTED_HEADING = '## What was and was not tested (kept by the runner, no model call)';
24
+
25
+ const NUM = '(-?\\d{1,9}(?:\\.\\d+)?)';
26
+ const READING = new RegExp(`([A-Za-z]{2,20})\\s*[:=]?\\s*${NUM}(?:\\s*(?:\\/|of|out of)\\s*${NUM})?`, 'g');
27
+ const GARBAGE = /([A-Za-z]{2,20})\s*[:=]\s*(NaN|undefined|Infinity|-Infinity|\[object Object\])(?![A-Za-z])/g;
28
+ /** Counts that cannot be less than nothing. Money that may be a debt by design is left out. */
29
+ export const NEVER_NEGATIVE = new Set(['lives', 'life', 'health', 'hp', 'ammo', 'coins', 'coin', 'gold', 'gems', 'stars', 'hearts', 'score', 'points', 'level', 'wave', 'round', 'energy', 'mana', 'stamina',
30
+ 'shield', 'armor', 'armour', 'items', 'keys', 'bombs', 'arrows', 'moves', 'turns', 'fuel', 'xp', 'exp', 'kills', 'combo', 'streak', 'food', 'wood', 'stone', 'ore', 'population', 'units', 'cards',
31
+ 'tokens', 'tickets', 'clicks', 'cookies', 'count', 'stock', 'supply', 'potions', 'oxygen', 'crystals', 'seeds', 'eggs', 'fish', 'apples', 'berries']);
32
+ /** Values printed as "now / most". */
33
+ export const BOUNDED = new Set(['health', 'hp', 'lives', 'life', 'energy', 'mana', 'stamina', 'shield', 'armor', 'armour', 'ammo', 'fuel', 'oxygen', 'hearts', 'hunger', 'progress', 'xp', 'exp', 'capacity']);
34
+ /** Totals that only go up during play. */
35
+ export const NEVER_FALLS = new Set(['score', 'points']);
36
+
37
+ /**
38
+ * The `label: number` readings in a text, the first of each label.
39
+ *
40
+ * @param {string} text
41
+ * @returns {Array<{label: string, value: number, max: number|null}>}
42
+ */
43
+ export function readings(text) {
44
+ const out = new Map();
45
+ for (const match of String(text || '').matchAll(READING)) {
46
+ const label = match[1].toLowerCase();
47
+ if (!out.has(label)) out.set(label, { label, value: Number(match[2]), max: match[3] === undefined ? null : Number(match[3]) });
48
+ }
49
+ return [...out.values()];
50
+ }
51
+
52
+ const VALUE = /(?:[:=,]\s*|^\s*)(undefined|null)(?=\s*(?:$|[.,;!?)\n]))/gm;
53
+ const TOKEN = /\[object [A-Z][A-Za-z]*\]|(?<![A-Za-z0-9])NaN(?![A-Za-z0-9])/g;
54
+ const TEMPLATE = /\{\d\}|\{\{\s*[A-Za-z_][\w.]*\s*\}\}|\$\{[A-Za-z_][\w.]*\}|%[sd](?![A-Za-z])|%\d\$[sd]/g;
55
+
56
+ /**
57
+ * Placeholder strings in text a player reads: a value never set, a template
58
+ * never filled in. A driver's own outline (node names, script paths) is not
59
+ * what a player reads, so only quoted text is checked.
60
+ *
61
+ * @param {string} text an observation
62
+ * @returns {Array<{shown: string, kind: 'value'|'template'}>}
63
+ */
64
+ export function placeholderStrings(text) {
65
+ const out = [];
66
+ const add = (shown, kind) => { const value = shown.trim().slice(0, 60); if (value && !out.some(entry => entry.shown === value)) out.push({ shown: value, kind }); };
67
+ // What sits between double quotes is what the game shows: a label, a button's text, a line of dialogue.
68
+ for (const quoted of String(text || '').matchAll(/"([^"\n]{1,300})"/g)) {
69
+ const shown = quoted[1];
70
+ for (const match of shown.matchAll(VALUE)) add(match[1], 'value');
71
+ for (const match of shown.matchAll(TOKEN)) add(match[0], 'value');
72
+ for (const match of shown.matchAll(TEMPLATE)) add(match[0], 'template');
73
+ }
74
+ return out.slice(0, 8);
75
+ }
76
+
77
+ // A control as the drivers print it: `button "Start"` (web), `Button BeginButton "Begin"` or `label="Rouen"` (Godot).
78
+ const WEB_CONTROL = /(?:^|[\s-])(button|link|checkbox|radio|tab|menuitem|switch|textbox|combobox|slider|option) "([^"\n]{1,80})"/gim;
79
+ const GODOT_CONTROL = /\b((?:[A-Z][A-Za-z]*)?Button|CheckBox|OptionButton|LineEdit|TextEdit|HSlider|VSlider|TabBar|ItemList)\s+([A-Za-z_][\w]*)(?:\s+(?:label=)?"([^"\n]{1,80})")?/g;
80
+
81
+ /**
82
+ * The controls an observation lists, by the name a player or an input would
83
+ * use for them.
84
+ *
85
+ * @param {string} text
86
+ * @returns {Array<{name: string, kind: string, node: string|null}>}
87
+ */
88
+ export function controlsIn(text) {
89
+ const out = new Map();
90
+ const source = String(text || '');
91
+ for (const match of source.matchAll(GODOT_CONTROL)) {
92
+ const name = (match[3] || match[2]).trim();
93
+ if (!out.has(name.toLowerCase())) out.set(name.toLowerCase(), { name: name.slice(0, 60), kind: match[1], node: match[2] });
94
+ }
95
+ for (const match of source.matchAll(WEB_CONTROL)) {
96
+ const name = match[2].trim();
97
+ if (!out.has(name.toLowerCase())) out.set(name.toLowerCase(), { name: name.slice(0, 60), kind: match[1].toLowerCase(), node: null });
98
+ }
99
+ return [...out.values()].slice(0, 60);
100
+ }
101
+
102
+ const digitless = value => String(value).replace(/\d+(?:[.,]\d+)*/g, '#').toLowerCase();
103
+
104
+ /**
105
+ * A stable id for a screen: the same controls (whatever numbers they carry)
106
+ * are the same screen, in this run and the next. A screen with fewer than
107
+ * two listed controls is known by the words on it.
108
+ *
109
+ * @param {string} text
110
+ * @param {string} [title]
111
+ * @returns {string}
112
+ */
113
+ export function screenId(text, title = '') {
114
+ const controls = controlsIn(text).map(control => digitless(control.name)).sort();
115
+ const basis = controls.length >= 2
116
+ ? `c:${controls.join('|')}`
117
+ : `t:${digitless(title)}|${digitless(String(text || '').replace(/\s+/g, ' ').trim().slice(0, 200))}`;
118
+ return `scr_${crypto.createHash('sha256').update(basis).digest('hex').slice(0, 8)}`;
119
+ }
120
+
121
+ /** What an input named, as lower-case text to look a control's name up in. */
122
+ function namedBy(record) {
123
+ if (!record || record.kind !== 'action') return '';
124
+ try { return JSON.stringify(record.input || {}).toLowerCase(); } catch { return ''; }
125
+ }
126
+
127
+ const quote = value => `"${String(value || '').replace(/"/g, "'").slice(0, 60)}"`;
128
+ const plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
129
+
130
+ /**
131
+ * The ledger for one run. `observe` takes each observation as the loop
132
+ * records it; `acted` takes each action record. Both are cheap and never
133
+ * throw on an odd shape.
134
+ */
135
+ export function createTesterLedger() {
136
+ const screens = new Map();
137
+ const last = new Map();
138
+ const healthy = new Map();
139
+ const told = new Map();
140
+ let current = null, observations = 0, withNumbers = 0, withText = 0;
141
+
142
+ const tell = (key, entry) => {
143
+ const known = told.get(key);
144
+ if (known) { known.seen += 1; known.lastObservation = entry.observation; return; }
145
+ told.set(key, { ...entry, seen: 1, lastObservation: entry.observation });
146
+ };
147
+
148
+ return {
149
+ /**
150
+ * @param {{index: number, text: string, title?: string, actions?: number, screenshot?: string|null}} observation
151
+ */
152
+ observe({ index, text, title = '', actions = 0, screenshot = null } = {}) {
153
+ observations += 1;
154
+ const body = String(text || '');
155
+ if (body.trim()) withText += 1;
156
+ const id = screenId(body, title);
157
+ let screen = screens.get(id);
158
+ if (!screen) {
159
+ // Named by its title only: the words on a screen are the game's, and are not copied into the report from here.
160
+ screen = { id, name: String(title || '').slice(0, 60), firstObservation: index, visits: 0, inputs: 0, controls: new Map() };
161
+ screens.set(id, screen);
162
+ }
163
+ if (current !== screen) screen.visits += 1;
164
+ current = screen;
165
+ for (const control of controlsIn(body)) {
166
+ const key = control.name.toLowerCase();
167
+ if (!screen.controls.has(key)) screen.controls.set(key, { ...control, tried: 0 });
168
+ }
169
+ const now = readings(body);
170
+ if (now.length > 0) withNumbers += 1;
171
+ const at = { observation: index, action: actions, screenshot };
172
+ for (const reading of now) {
173
+ const before = last.get(reading.label), ok = healthy.get(reading.label);
174
+ let broken = false;
175
+ if (reading.value < 0 && NEVER_NEGATIVE.has(reading.label)) {
176
+ broken = true;
177
+ if (ok) tell(`negative:${reading.label}`, { kind: 'negative', label: reading.label, from: ok.value, to: reading.value, ...at });
178
+ }
179
+ if (reading.max !== null && reading.max > 0 && reading.value > reading.max && BOUNDED.has(reading.label)) {
180
+ broken = true;
181
+ if (ok && ok.max !== null) tell(`above_max:${reading.label}`, { kind: 'above_max', label: reading.label, from: ok.value, to: reading.value, max: reading.max, ...at });
182
+ }
183
+ if (before && NEVER_FALLS.has(reading.label) && reading.value < before.value && reading.value > 0 && before.value > 0) tell(`fell:${reading.label}`, { kind: 'fell', label: reading.label, from: before.value, to: reading.value, ...at });
184
+ last.set(reading.label, { value: reading.value, max: reading.max });
185
+ if (!broken) healthy.set(reading.label, { value: reading.value, max: reading.max });
186
+ }
187
+ for (const match of body.matchAll(GARBAGE)) tell(`not_a_number:${match[1].toLowerCase()}`, { kind: 'not_a_number', label: match[1].toLowerCase(), from: last.get(match[1].toLowerCase())?.value ?? null, to: match[2], ...at });
188
+ for (const placeholder of placeholderStrings(body)) tell(`placeholder:${placeholder.shown}`, { kind: 'placeholder', shown: placeholder.shown, what: placeholder.kind, ...at });
189
+ return id;
190
+ },
191
+ /** An input was sent on the screen last observed. */
192
+ acted(record) {
193
+ if (!current || !record || record.kind !== 'action') return;
194
+ current.inputs += 1;
195
+ const named = namedBy(record);
196
+ if (!named) return;
197
+ for (const [key, control] of current.controls) {
198
+ if (named.includes(JSON.stringify(key).slice(1, -1)) || (control.node && named.includes(control.node.toLowerCase()))) control.tried += 1;
199
+ }
200
+ },
201
+ /** What the ledger saw that breaks a rule: each once, with how many observations showed it. */
202
+ violations() { return [...told.values()]; },
203
+ summary() {
204
+ const list = [...screens.values()].map(screen => {
205
+ const controls = [...screen.controls.values()];
206
+ return { id: screen.id, name: screen.name, firstObservation: screen.firstObservation, visits: screen.visits, inputs: screen.inputs, tried: controls.filter(control => control.tried).map(control => control.name), untried: controls.filter(control => !control.tried).map(control => control.name) };
207
+ });
208
+ return {
209
+ observations, withText, withNumbers, labels: [...last.keys()].slice(0, 20),
210
+ screens: list,
211
+ totals: { screens: list.length, controls: list.reduce((sum, screen) => sum + screen.tried.length + screen.untried.length, 0), tried: list.reduce((sum, screen) => sum + screen.tried.length, 0), untried: list.reduce((sum, screen) => sum + screen.untried.length, 0) }
212
+ };
213
+ }
214
+ };
215
+ }
216
+
217
+ /** How often the runner saw it: the ledger never tries anything again by itself, and says so. */
218
+ function seenWords(entry) {
219
+ return entry.seen > 1
220
+ ? `The runner saw it on ${entry.seen} observations (${entry.observation} to ${entry.lastObservation}); it did not try it again from a fresh start.`
221
+ : 'Seen once by the runner; it was not tried again.';
222
+ }
223
+
224
+ /**
225
+ * The ledger's violations as runner findings (./honesty.js), each tied to the
226
+ * observation and action it was seen at.
227
+ *
228
+ * @param {ReturnType<typeof createTesterLedger>} ledger
229
+ * @param {{actionRecords?: Array<Object>}} [context]
230
+ * @returns {Array<Object>}
231
+ */
232
+ export function testerFindings(ledger, { actionRecords = [] } = {}) {
233
+ if (!ledger) return [];
234
+ const out = [];
235
+ const placeholders = [];
236
+ for (const entry of ledger.violations()) {
237
+ if (entry.kind === 'placeholder') { placeholders.push(entry); continue; }
238
+ const label = `"${entry.label}"`;
239
+ const where = `at observation ${entry.observation}, after ${plural(entry.action, 'action')}`;
240
+ const words = {
241
+ negative: [`${label} goes below zero`, `The game showed ${label} at ${entry.to} ${where}. It was ${entry.from} before. A count of this kind cannot be less than nothing, so something was taken without checking that enough was left.`, 'major'],
242
+ above_max: [`${label} goes above its maximum`, `The game showed ${label} at ${entry.to} of ${entry.max} ${where}. It was ${entry.from} before. The value passed the limit the game itself prints beside it.`, 'major'],
243
+ fell: [`${label} went down`, `The game showed ${label} falling from ${entry.from} to ${entry.to} ${where}, without starting again from zero. If the game takes points away on purpose this is by design; if not, the total is being counted wrongly.`, 'minor'],
244
+ not_a_number: [`${label} shows "${entry.to}" where a number belongs`, `The game printed ${label} as "${entry.to}" ${where}. A value that is not a number reached the screen, which usually means a sum went wrong in the game's code.`, 'major']
245
+ }[entry.kind];
246
+ out.push(runnerFinding({ severity: words[2], category: 'bug', title: words[0], description: `${words[1]} ${seenWords(entry)}`, steps: stepsBefore(actionRecords), screenshot: entry.screenshot, action: entry.action, key: `tester:${entry.kind}:${entry.label}` }));
247
+ }
248
+ if (placeholders.length > 0) {
249
+ const first = placeholders[0];
250
+ const kind = what => (what === 'template' ? 'a template that was never filled in' : 'a value that was never set');
251
+ out.push(runnerFinding({
252
+ severity: 'minor', category: 'content', title: `Placeholder text is shown on screen: ${quote(first.shown)}`,
253
+ description: `The game's own text shows ${placeholders.slice(0, 5).map(entry => `${quote(entry.shown)} (${kind(entry.what)}) at observation ${entry.observation}`).join('; ')}. A player sees the raw string where words or a number belong. ${seenWords(first)}`,
254
+ steps: stepsBefore(actionRecords), screenshot: first.screenshot, action: first.action, key: 'tester:placeholder'
255
+ }));
256
+ }
257
+ return out;
258
+ }
259
+
260
+ const EDGE_NAMES = Object.freeze({ focus: 'Focus loss and return', resize: 'Window resize, a phone-sized window included', rapid: 'Rapid input', idle: 'Idling', reload: 'A reload in the middle of the game' });
261
+
262
+ /**
263
+ * The section for report.md: the scripted checks that ran and did not, what
264
+ * the runner's own oracles could read, and the screens and controls.
265
+ *
266
+ * @param {ReturnType<typeof createTesterLedger>} ledger
267
+ * @param {{edge?: Object|null}} [context]
268
+ * @returns {string}
269
+ */
270
+ export function testedMarkdown(ledger, { edge = null, probes = null } = {}) {
271
+ if (!ledger) return '';
272
+ const summary = ledger.summary();
273
+ const lines = ['Not tested never means it works, and a check that found nothing says only that nothing went wrong in that check.', ''];
274
+ lines.push('Scripted checks (the runner, after play):');
275
+ lines.push('');
276
+ const checks = edge && Array.isArray(edge.checks) ? edge.checks : [];
277
+ for (const [name, title] of Object.entries(EDGE_NAMES)) {
278
+ const found = checks.filter(check => check.name === name);
279
+ if (found.length === 0) lines.push(`- ${title}: not tested. ${edge ? 'The checks ended before it.' : 'The scripted checks did not run on this driver or this run.'}`);
280
+ else if (found.every(check => check.status === 'not_checked')) lines.push(`- ${title}: not tested. ${String(found[0].detail || '').replace(/\.?$/, '.')}`);
281
+ else lines.push(`- ${title}: tested, ${found.some(check => check.status === 'problem') ? 'and a problem was found (see the edge behaviour section)' : 'and nothing went wrong in this check'}.`);
282
+ }
283
+ if (probes && Array.isArray(probes.checks) && probes.checks.length > 0) {
284
+ const ran = probes.checks.filter(check => check.status !== 'not_checked'), not = probes.checks.filter(check => check.status === 'not_checked');
285
+ lines.push(`- The tester probes (rapid input, buttons never named, text fields, a menu left and entered again, pause, opposite keys, the edges, the wrong order, input while loading): ${ran.length} ran and ${not.length} did not. Each is listed under the tester probes heading, with why one was not tested.`);
286
+ } else lines.push('- Rapid repeats on one control, opposite keys together, pause and resume, a menu left and entered again, text fields given nothing, too much and odd text, the edges of the play area, steps out of order: not tested by the runner on this driver. Only what the persona wrote about them was tested.');
287
+ lines.push('');
288
+ lines.push('What the runner watched while the persona played:');
289
+ lines.push('');
290
+ lines.push(summary.withNumbers > 0
291
+ ? `- The game's own numbers (a counter below zero, a value above its maximum, a score that falls, a value that is not a number): watched on ${plural(summary.withNumbers, 'observation')} (${summary.labels.slice(0, 8).join(', ')}).`
292
+ : '- The game\'s own numbers: not tested. No observation showed a labelled number as text (numbers drawn in a picture are not read).');
293
+ lines.push(summary.withText > 0
294
+ ? `- Placeholder text (a value never set, a template never filled in): checked in the quoted text of ${plural(summary.withText, 'observation')}.`
295
+ : '- Placeholder text: not tested. No observation carried text.');
296
+ lines.push(probes ? '- Trying a suspected bug again: each finding of a probe says how often it came back in the session, and the run\'s replay runs the probe once more. The persona\'s own findings should say "Reproduced n of m" or "Seen once".' : '- Trying a suspected bug again: left to the persona (each of its findings should say "Reproduced n of m" or "Seen once").');
297
+ lines.push('');
298
+ if (summary.screens.length === 0) { lines.push('No screen was recorded.'); return lines.join('\n'); }
299
+ const t = summary.totals;
300
+ lines.push(`Screens and controls: ${plural(t.screens, 'screen')} seen. Of ${plural(t.controls, 'listed control')}, ${t.tried} ${t.tried === 1 ? 'was' : 'were'} named by an input and ${t.untried} never ${t.untried === 1 ? 'was' : 'were'}. A control that was not tried was not tested: nothing here says it works. An input sent by coordinates names no control, so a control tried that way is listed as not tried.`);
301
+ lines.push('');
302
+ lines.push('| Screen | First seen | Inputs | Tried | Never tried |');
303
+ lines.push('| --- | --- | --- | --- | --- |');
304
+ const cell = value => String(value).replace(/\|/g, '/').replace(/[\r\n]+/g, ' ');
305
+ const names = (list, max) => (list.length === 0 ? 'none' : `${list.slice(0, max).map(quote).join(', ')}${list.length > max ? ` and ${list.length - max} more` : ''}`);
306
+ for (const screen of summary.screens.slice(0, 12)) lines.push(`| ${cell(`${screen.name ? `${quote(screen.name)} ` : ''}(${screen.id})`)} | observation ${screen.firstObservation} | ${screen.inputs} | ${cell(names(screen.tried, 5))} | ${cell(screen.tried.length + screen.untried.length === 0 ? 'no controls are listed for it' : names(screen.untried, 6))} |`);
307
+ if (summary.screens.length > 12) lines.push(`| ${summary.screens.length - 12} more screens | | | | |`);
308
+ // A screen's title and its controls' names are the game's own words: anything secret shaped in them stays out of the report.
309
+ return redactSecrets(lines.join('\n').replace(/[\u2013\u2014]/g, ','));
310
+ }
311
+
312
+ export default { createTesterLedger, testerFindings, testedMarkdown, readings, placeholderStrings, controlsIn, screenId };