ravensight-playtest 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +266 -44
  2. package/addons/ravensight_driver/driver.gd +704 -21
  3. package/docs/ADAPTERS.md +11 -7
  4. package/docs/NATIVE_RUNNER.md +3 -1
  5. package/docs/godot-driver.md +136 -13
  6. package/package.json +8 -6
  7. package/src/api/client.js +4 -3
  8. package/src/cli.js +114 -13
  9. package/src/commands/check.js +30 -4
  10. package/src/commands/fakeCore.js +14 -2
  11. package/src/commands/hosted.js +18 -4
  12. package/src/commands/init.js +17 -1
  13. package/src/commands/run.js +209 -14
  14. package/src/commands/upload.js +6 -2
  15. package/src/commands/validate.js +1 -1
  16. package/src/commands/validateHosted.js +50 -5
  17. package/src/config.js +33 -2
  18. package/src/hosted/archivePreflight.js +7 -7
  19. package/src/hosted/buildUpload.js +89 -8
  20. package/src/hosted/recordedRun.js +40 -1
  21. package/src/run/actionSelector.js +14 -3
  22. package/src/run/aggregate.js +57 -3
  23. package/src/run/anygame/controlbook.js +179 -0
  24. package/src/run/anygame/genre.js +179 -0
  25. package/src/run/anygame/index.js +258 -0
  26. package/src/run/anygame/language.js +336 -0
  27. package/src/run/anygame/memory.js +330 -0
  28. package/src/run/anygame/shared-hashes.json +10 -0
  29. package/src/run/anygame/shared.js +24 -0
  30. package/src/run/anygame/sound.js +342 -0
  31. package/src/run/args.js +75 -8
  32. package/src/run/captureCheck.js +161 -0
  33. package/src/run/choiceCheck.js +312 -0
  34. package/src/run/claimGate.js +236 -0
  35. package/src/run/context.js +254 -13
  36. package/src/run/drivers/godot-observation.js +93 -6
  37. package/src/run/drivers/godot.js +769 -46
  38. package/src/run/drivers/recording.js +24 -4
  39. package/src/run/drivers/web.js +1242 -77
  40. package/src/run/edgePass.js +731 -0
  41. package/src/run/fixLoop.js +5 -4
  42. package/src/run/focus.js +65 -0
  43. package/src/run/gamepad.js +108 -0
  44. package/src/run/godotEdgePass.js +235 -0
  45. package/src/run/godotTesterProbes.js +192 -0
  46. package/src/run/headings.js +21 -0
  47. package/src/run/honesty.js +642 -0
  48. package/src/run/inputs.js +256 -0
  49. package/src/run/marks.js +142 -0
  50. package/src/run/personaLoop.js +1128 -120
  51. package/src/run/phone.js +7 -0
  52. package/src/run/pixels.js +215 -0
  53. package/src/run/playClock.js +162 -0
  54. package/src/run/readiness.js +585 -0
  55. package/src/run/refusal.js +67 -0
  56. package/src/run/regions.js +119 -0
  57. package/src/run/report.js +14 -2
  58. package/src/run/reportChecks.js +487 -0
  59. package/src/run/resume.js +3 -2
  60. package/src/run/screenshots.js +161 -0
  61. package/src/run/strip.js +114 -0
  62. package/src/run/testerLedger.js +312 -0
  63. package/src/run/testerProbes.js +584 -0
  64. package/src/run/thinRun.js +102 -0
  65. package/src/run/timeFreeze.js +79 -0
  66. package/src/run/tools.js +454 -29
  67. package/src/runDefaults.js +1 -0
@@ -0,0 +1,336 @@
1
+ // Languages: which one a brief or a game's screen is written in, and the
2
+ // parts of the playtester that used to read English only (PE-02, RM-08 in
3
+ // docs/playtest/PLAYTESTER_EDGE_CASES.md): splitting a brief into goals,
4
+ // matching its "stay out of" lines, knowing a button that moves on, finding a
5
+ // test code, and choosing the language the report's prose is written in.
6
+ //
7
+ // Detection is by script first (kana, Hangul, Han, Cyrillic and so on), then
8
+ // by function words for languages that share the Latin alphabet. It is a
9
+ // measure of the text, not a model call. A text too short to tell is `null`,
10
+ // never a guess.
11
+ //
12
+ // Pure: no I/O, no page, no model. The same file is carried by the hosted runner
13
+ // (the platform repo, infrastructure/hosted-playtest/direct-runner/lib/anygame/language.mjs).
14
+
15
+ const norm = s => String(s ?? '').normalize('NFKC');
16
+ const fold = s => norm(s).toLowerCase();
17
+
18
+ export const LANGUAGES = Object.freeze({
19
+ en: { name: 'English', native: ['english'] },
20
+ ja: { name: 'Japanese', native: ['日本語', 'japanese', 'にほんご'] },
21
+ zh: { name: 'Chinese', native: ['中文', '汉语', '漢語', '简体中文', '繁體中文', 'chinese', 'mandarin'] },
22
+ ko: { name: 'Korean', native: ['한국어', '한글', 'korean'] },
23
+ ru: { name: 'Russian', native: ['русский', 'русском', 'russian'] },
24
+ uk: { name: 'Ukrainian', native: ['українська', 'українською', 'ukrainian'] },
25
+ ar: { name: 'Arabic', native: ['العربية', 'arabic'] },
26
+ he: { name: 'Hebrew', native: ['עברית', 'hebrew'] },
27
+ th: { name: 'Thai', native: ['ไทย', 'thai'] },
28
+ hi: { name: 'Hindi', native: ['हिन्दी', 'हिंदी', 'hindi'] },
29
+ el: { name: 'Greek', native: ['ελληνικά', 'greek'] },
30
+ es: { name: 'Spanish', native: ['español', 'castellano', 'spanish'] },
31
+ fr: { name: 'French', native: ['français', 'french'] },
32
+ de: { name: 'German', native: ['deutsch', 'german'] },
33
+ pt: { name: 'Portuguese', native: ['português', 'portuguese'] },
34
+ it: { name: 'Italian', native: ['italiano', 'italian'] },
35
+ nl: { name: 'Dutch', native: ['nederlands', 'dutch'] },
36
+ pl: { name: 'Polish', native: ['polski', 'polsku', 'polish'] },
37
+ tr: { name: 'Turkish', native: ['türkçe', 'turkish'] },
38
+ sv: { name: 'Swedish', native: ['svenska', 'swedish'] },
39
+ id: { name: 'Indonesian', native: ['bahasa indonesia', 'indonesian'] },
40
+ vi: { name: 'Vietnamese', native: ['tiếng việt', 'vietnamese'] }
41
+ });
42
+
43
+ export const languageName = code => LANGUAGES[code]?.name || null;
44
+
45
+ // Scripts that name a language on their own, most telling first.
46
+ const SCRIPTS = [
47
+ ['ja', /[\p{Script=Hiragana}\p{Script=Katakana}]/gu],
48
+ ['ko', /\p{Script=Hangul}/gu],
49
+ ['zh', /\p{Script=Han}/gu],
50
+ ['ru', /\p{Script=Cyrillic}/gu],
51
+ ['ar', /\p{Script=Arabic}/gu],
52
+ ['he', /\p{Script=Hebrew}/gu],
53
+ ['th', /\p{Script=Thai}/gu],
54
+ ['hi', /\p{Script=Devanagari}/gu],
55
+ ['el', /\p{Script=Greek}/gu]
56
+ ];
57
+ const UKRAINIAN = /[іїєґ]/giu;
58
+
59
+ // Function words of languages written in the Latin alphabet. A word counts
60
+ // once per use; the language with the most is the text's, when it leads.
61
+ const WORDS = {
62
+ en: 'the and you to of is in it that for with this are your on not be can will press start play click when then have what from',
63
+ es: 'el la los las de que y en un una es por con para no se su al lo como más pero sus le ya jugar pulsa nivel',
64
+ fr: 'le la les de des et en un une est que pour dans pas vous sur au avec ce qui ne se du jouer appuyez niveau',
65
+ de: 'der die das und ist nicht ein eine zu den mit für auf dem von sie es im wir du spielen drücke stufe oder',
66
+ pt: 'o a os as de que e em um uma é por com para não se do da no na mais como jogar pressione nível você',
67
+ it: 'il lo la i gli le di che e in un una è per con non si del della dei più come gioca premi livello sono',
68
+ nl: 'de het een en van is niet in op te dat voor met zijn je naar aan om ook spelen druk niveau maar',
69
+ pl: 'i w na nie z do się to jest że jak ale po co tak za od czy graj naciśnij poziom być',
70
+ tr: 've bir bu için ile de da ne gibi daha çok en mi ama oyna bas seviye olarak var',
71
+ sv: 'och att det en ett är inte på för med som den av till har du jag spela tryck nivå om',
72
+ id: 'yang dan di ke dari untuk dengan ini itu tidak ada pada akan atau main tekan tingkat kamu',
73
+ vi: 'và của là có không cho một các được trong để với này người chơi nhấn cấp độ'
74
+ };
75
+ const WORD_SETS = Object.fromEntries(Object.entries(WORDS).map(([k, v]) => [k, new Set(v.split(' '))]));
76
+ // Letters only one of them uses: a strong sign in a short text (a menu of three words).
77
+ const MARKS = { es: /[ñ¿¡]/giu, fr: /[çœêèàù]/giu, de: /[äöüß]/giu, pt: /[ãõ]/giu, pl: /[ąęłńśźż]/giu, tr: /[ğışİ]/gu, sv: /[å]/giu, vi: /[ăđơưạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ]/giu };
78
+
79
+ // The least text a verdict is given on: letters in a script that names its
80
+ // language, or words in the Latin alphabet.
81
+ export const MIN_SCRIPT_LETTERS = 2;
82
+ export const MIN_LATIN_WORDS = 3;
83
+
84
+ /**
85
+ * The language a text is written in: `{ code, name, script, share }`, or null
86
+ * when there is too little of it to say. `share` is the part of the text's
87
+ * letters (or words) that speak for the verdict.
88
+ */
89
+ export function detectLanguage(text) {
90
+ const t = norm(text);
91
+ const letters = (t.match(/\p{L}/gu) || []).length;
92
+ if (!letters) return null;
93
+ const counts = SCRIPTS.map(([code, re]) => [code, (t.match(re) || []).length]);
94
+ const by = Object.fromEntries(counts);
95
+ // Kana beside Han is Japanese; Han alone is Chinese.
96
+ if (by.ja >= MIN_SCRIPT_LETTERS || (by.ja >= 1 && by.zh >= 1)) return verdict('ja', (by.ja + by.zh) / letters, 'kana');
97
+ const [top, n] = counts.filter(([c]) => c !== 'ja').sort((a, b) => b[1] - a[1])[0];
98
+ if (n >= MIN_SCRIPT_LETTERS && n >= 0.3 * letters) {
99
+ if (top === 'ru' && (t.match(UKRAINIAN) || []).length) return verdict('uk', n / letters, 'cyrillic');
100
+ return verdict(top, n / letters, top === 'ru' ? 'cyrillic' : top === 'zh' ? 'han' : top);
101
+ }
102
+ const words = fold(t).match(/\p{L}+/gu) || [];
103
+ if (words.length < MIN_LATIN_WORDS) return null;
104
+ const score = {};
105
+ for (const [code, set] of Object.entries(WORD_SETS)) score[code] = words.reduce((k, w) => k + (set.has(w) ? 1 : 0), 0);
106
+ for (const [code, re] of Object.entries(MARKS)) score[code] += 2 * (t.match(re) || []).length;
107
+ const ranked = Object.entries(score).sort((a, b) => b[1] - a[1]);
108
+ const [best, hits] = ranked[0];
109
+ // A lead of one word over the runner-up is not a verdict; a tie goes to nobody.
110
+ if (hits < 2 || hits - ranked[1][1] < 1 || hits < 0.12 * words.length) return null;
111
+ return verdict(best, Math.min(1, hits / words.length), 'latin');
112
+ }
113
+
114
+ function verdict(code, share, script) {
115
+ return { code, name: languageName(code), script, share: Math.round(Math.min(1, share) * 100) / 100 };
116
+ }
117
+
118
+ // Words that say "the report", in the languages above.
119
+ const REPORT_WORDS = ['report', 'findings', 'write up', 'writeup', 'feedback', 'answer', 'respond', 'reply', 'レポート', '報告', '回答', 'フィードバック', '报告', '報告', '反馈', '回复', '리포트', '보고서', '보고', '피드백', 'informe', 'reporte', 'rapport', 'bericht', 'relatório', 'rapporto', 'отчет', 'отчёт', 'raport', 'rapor'];
120
+ const REPORT_WINDOW = 40;
121
+
122
+ /**
123
+ * The language a brief asks its report to be written in ("write the report in
124
+ * English", 「レポートは英語で」), or null when it does not say. A language is
125
+ * taken only when it is named within a few words of the report itself, so
126
+ * "the game is in Japanese" asks for nothing.
127
+ */
128
+ export function requestedReportLanguage(brief) {
129
+ const t = fold(brief);
130
+ if (!t) return null;
131
+ const spots = [];
132
+ for (const w of REPORT_WORDS) for (let i = t.indexOf(w); i >= 0; i = t.indexOf(w, i + 1)) spots.push([i, i + w.length]);
133
+ if (!spots.length) return null;
134
+ let best = null;
135
+ for (const [code, lang] of Object.entries(LANGUAGES)) {
136
+ for (const name of [...lang.native, ...(code === 'en' ? ['英語', '英文', '영어', 'inglés', 'anglais', 'englisch', 'inglês', 'inglese', 'английском', 'английский'] : []), ...(code === 'ja' ? ['日本語'] : [])]) {
137
+ const n = fold(name);
138
+ for (let i = t.indexOf(n); i >= 0; i = t.indexOf(n, i + 1)) {
139
+ // A Latin name must stand as a word ("german", not "germane").
140
+ if (/^[a-z ]+$/.test(n) && (/[a-z]/.test(t[i - 1] || '') || /[a-z]/.test(t[i + n.length] || ''))) continue;
141
+ const gap = Math.min(...spots.map(([a, b]) => (i >= b ? i - b : a >= i + n.length ? a - (i + n.length) : 0)));
142
+ if (gap <= REPORT_WINDOW && (!best || gap < best.gap)) best = { code, gap };
143
+ }
144
+ }
145
+ }
146
+ return best ? best.code : null;
147
+ }
148
+
149
+ /**
150
+ * The language the report's prose is written in: the one the brief asks for,
151
+ * else the brief's own, else English. `{ code, name, why }`.
152
+ */
153
+ export function reportLanguage(brief, { explicit = null } = {}) {
154
+ const told = typeof explicit === 'string' && LANGUAGES[explicit.toLowerCase().slice(0, 2)] ? explicit.toLowerCase().slice(0, 2) : null;
155
+ if (told) return { code: told, name: languageName(told), why: 'the job asked for it' };
156
+ const asked = requestedReportLanguage(brief);
157
+ if (asked) return { code: asked, name: languageName(asked), why: 'the brief asked for it' };
158
+ const own = detectLanguage(brief);
159
+ if (own) return { code: own.code, name: own.name, why: 'it is the language the brief is written in' };
160
+ return { code: 'en', name: 'English', why: 'the brief was too short to tell its language' };
161
+ }
162
+
163
+ // What separates one goal from the next in a brief: punctuation in any
164
+ // script, a line break, a list marker, and "then" in the languages above.
165
+ const GOAL_BREAK = /\s*(?:[;;。。!!??\n\r]+|\.(?=\s|$)|[,,、、])\s*(?:(?:\d{1,2}[.)]|[•·・*-])\s+)?/u;
166
+ const THEN_WORDS = ['and then', 'then', 'after that', 'afterwards', 'その後', 'そのあと', 'それから', '次に', 'そして', '然后', '然後', '接着', '接著', '之后', '之後', '그리고 나서', '그 다음', '그다음', '그리고', '다음에', 'luego', 'después', 'y luego', 'entonces', 'puis', 'ensuite', 'et ensuite', 'dann', 'danach', 'anschließend', 'depois', 'em seguida', 'então', 'poi', 'quindi', 'затем', 'потом', 'после этого', 'potem', 'następnie', 'sonra', 'ardından', 'daarna', 'vervolgens', 'sedan', 'därefter', 'lalu', 'kemudian', 'sau đó', 'rồi'];
167
+ const THEN_SPLIT = new RegExp(`\\s*(?:${THEN_WORDS.sort((a, b) => b.length - a.length).map(w => (/^[\x20-\x7e]+$/.test(w) ? `(?<![\\p{L}])${w}(?![\\p{L}])` : w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('|')})\\s*`, 'iu');
168
+ // Clauses that ask the tester to watch for something are instructions about the report, not goals of play.
169
+ const NOTICE_START = /^(?:and\s+)?(?:notice|note|report|tell|watch|look out|keep an eye|mention|気づいた|気になった|報告|メモ|注意|记录|記錄|报告|注意到|보고|메모|anota|informa|notez|signalez|notiere|melde|anote|relate|annota|segnala|отметь|сообщи)/iu;
170
+ export const GOAL_LIMITS = { min: 2, minLatin: 4, max: 160, count: 6 };
171
+
172
+ /**
173
+ * A brief's goals in order, in whatever language it is written in: the
174
+ * clauses after its first colon, split on punctuation of any script, list
175
+ * markers and "then". Null when the brief does not hold at least two, so the
176
+ * caller keeps its defaults.
177
+ */
178
+ export function splitGoals(objective) {
179
+ let t = norm(objective).replace(/[ \t ]+/g, ' ').trim();
180
+ if (!t) return null;
181
+ const colon = t.search(/[::]/u);
182
+ if (colon >= 0 && colon < 160) t = t.slice(colon + 1);
183
+ const parts = t.split(GOAL_BREAK).flatMap(p => String(p || '').split(THEN_SPLIT))
184
+ .map(s => String(s || '').trim().replace(/^(?:and|then|y|et|und|e|и|と|そして)\s+/iu, '').replace(/[.。!?!?\s]+$/u, ''))
185
+ .filter(s => {
186
+ const min = /[^\x20-\x7e]/.test(s) ? GOAL_LIMITS.min : GOAL_LIMITS.minLatin;
187
+ return [...s].length >= min && [...s].length <= GOAL_LIMITS.max && /\p{L}/u.test(s) && !NOTICE_START.test(s);
188
+ });
189
+ return parts.length >= 2 ? parts.slice(0, GOAL_LIMITS.count) : null;
190
+ }
191
+
192
+ // Words in a "stay out of" line that name nothing: articles, "menu", "do not".
193
+ const AVOID_NOISE = new Set(('the a an menu screen page don\'t dont do not skip avoid open never stay out of any and or el la los las un una no abrir evitar le les des ne pas ouvrir éviter der die das nicht öffnen vermeiden o os as não abrir il lo non aprire не открывать'
194
+ ).split(' '));
195
+ // Particles and verb endings that hang on a name in Japanese, Chinese and Korean avoid lines.
196
+ const CJK_NOISE = /(?:しないでください|でください|ください|下さい|しないで|しないこと|は開かない|を開かない|開かない|に入らない|入らない|には触れない|触れない|を避ける|避ける|は使わない|使わない|禁止|画面|メニュー|ページ|不要打开|不要打開|不要进入|不要進入|不要点击|不要點擊|不要|别|別|避免|请勿|請勿|勿|界面|菜单|選單|页面|頁面|하지 마세요|하지 마|열지 마세요|열지 마|들어가지 마세요|들어가지 마|피하세요|피하기|금지|화면|메뉴|페이지|(?<=[\p{Script=Han}\p{Script=Katakana}ー])[はをにがでのもへと]|[、。]|(?<=\p{Script=Hangul})[은는이가을를에의도](?=\s|$))/gu;
197
+
198
+ /** The words of a "stay out of" line that must all be in an option's description for it to match. */
199
+ export function avoidTerms(line) {
200
+ // Particles and "do not open" endings come off the whole line first: some of them span a space.
201
+ const t = fold(line).replace(CJK_NOISE, ' ');
202
+ const out = [];
203
+ const SPACELESS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}ー]+/gu;
204
+ // A run of letters in a script without spaces is a term as it stands.
205
+ for (const run of t.match(SPACELESS) || []) if ([...run].length >= 2) out.push(run);
206
+ for (const w of t.replace(SPACELESS, ' ').match(/[\p{L}\p{N}']+/gu) || []) {
207
+ if ([...w].length >= 3 && !AVOID_NOISE.has(w)) out.push(w);
208
+ }
209
+ return [...new Set(out)];
210
+ }
211
+
212
+ /** True when an option's words name something the studio said to stay out of, in any language. */
213
+ export function avoidedIn(description, avoid = []) {
214
+ const d = fold(description);
215
+ return (Array.isArray(avoid) ? avoid : []).some(line => {
216
+ const terms = avoidTerms(line);
217
+ return terms.length > 0 && terms.every(w => d.includes(w));
218
+ });
219
+ }
220
+
221
+ // A control that moves the player on (Back, Close, Continue, Next, OK, Play,
222
+ // Start, Resume, Done, Skip), as games label it in the languages above.
223
+ const GOING_ON_LATIN = ['back', 'close', 'cancel', 'continue', 'next', 'ok', 'okay', 'play', 'start', 'resume', 'done', 'skip', 'retry', 'again',
224
+ 'volver', 'atrás', 'cerrar', 'cancelar', 'continuar', 'siguiente', 'jugar', 'empezar', 'comenzar', 'iniciar', 'reanudar', 'listo', 'saltar', 'omitir', 'reintentar', 'aceptar',
225
+ 'retour', 'fermer', 'annuler', 'continuer', 'suivant', 'jouer', 'commencer', 'démarrer', 'reprendre', 'terminé', 'passer', 'réessayer',
226
+ 'zurück', 'schließen', 'abbrechen', 'weiter', 'spielen', 'starten', 'fortsetzen', 'fertig', 'überspringen', 'nochmal',
227
+ 'voltar', 'fechar', 'próximo', 'jogar', 'começar', 'retomar', 'pronto', 'pular', 'tentar',
228
+ 'indietro', 'chiudi', 'annulla', 'continua', 'avanti', 'gioca', 'inizia', 'riprendi', 'fatto', 'salta', 'riprova',
229
+ 'назад', 'закрыть', 'отмена', 'продолжить', 'далее', 'играть', 'начать', 'старт', 'готово', 'пропустить', 'заново',
230
+ 'wstecz', 'zamknij', 'anuluj', 'kontynuuj', 'dalej', 'graj', 'gotowe', 'pomiń',
231
+ 'geri', 'kapat', 'iptal', 'devam', 'ileri', 'oyna', 'başla', 'tamam', 'atla',
232
+ 'terug', 'sluiten', 'annuleren', 'doorgaan', 'volgende', 'spelen', 'klaar', 'overslaan',
233
+ 'tillbaka', 'stäng', 'avbryt', 'fortsätt', 'nästa', 'spela', 'starta', 'klar', 'hoppa',
234
+ 'kembali', 'tutup', 'batal', 'lanjut', 'lanjutkan', 'berikutnya', 'main', 'mulai', 'selesai', 'lewati'];
235
+ const GOING_ON_OTHER = ['戻る', 'もどる', '閉じる', 'とじる', 'キャンセル', '続ける', 'つづける', 'つづきから', '次へ', 'つぎへ', '進む', 'すすむ', 'プレイ', 'スタート', 'はじめる', '始める', 'はじめから', '開始', '再開', '完了', 'スキップ', 'もう一度', 'リトライ', 'やり直す', '決定', 'はい',
236
+ '返回', '关闭', '關閉', '取消', '继续', '繼續', '下一步', '下一关', '下一關', '开始', '開始', '开始游戏', '開始遊戲', '完成', '跳过', '跳過', '重试', '重試', '再来一次', '确定', '確定', '好的',
237
+ '뒤로', '닫기', '취소', '계속', '다음', '플레이', '시작', '게임 시작', '재개', '완료', '건너뛰기', '다시', '재시도', '확인',
238
+ 'رجوع', 'إغلاق', 'إلغاء', 'متابعة', 'التالي', 'العب', 'ابدأ', 'تم', 'تخطي',
239
+ 'חזרה', 'סגור', 'ביטול', 'המשך', 'הבא', 'שחק', 'התחל', 'סיום', 'דלג',
240
+ 'ย้อนกลับ', 'ปิด', 'ยกเลิก', 'ต่อไป', 'ถัดไป', 'เล่น', 'เริ่ม', 'เสร็จ', 'ข้าม',
241
+ 'πίσω', 'κλείσιμο', 'ακύρωση', 'συνέχεια', 'επόμενο', 'παίξε', 'έναρξη'];
242
+ const GOING_ON_WORD = new RegExp(`(?<![\\p{L}\\p{N}])(?:${GOING_ON_LATIN.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})(?![\\p{L}\\p{N}])`, 'iu');
243
+
244
+ /** Whether a control's label is one that moves the player on, in any of the languages above. */
245
+ export function goingOn(name) {
246
+ const t = fold(name);
247
+ if (!t) return false;
248
+ return GOING_ON_WORD.test(t) || GOING_ON_OTHER.some(w => t.includes(w));
249
+ }
250
+
251
+ // A test code named in a brief: "code ABC123", 「コード: 4417」, "código ABC123".
252
+ const CODE_WORDS = ['code', 'passcode', 'password', 'コード', 'パスコード', '暗証番号', 'パスワード', '合言葉', '代码', '代碼', '验证码', '驗證碼', '密码', '密碼', '코드', '암호', '비밀번호', 'código', 'codigo', 'contraseña', 'mot de passe', 'kennwort', 'passwort', 'senha', 'codice', 'код', 'пароль', 'kod', 'hasło', 'şifre', 'kode'];
253
+ const CODE_RE = new RegExp(`(?:${CODE_WORDS.sort((a, b) => b.length - a.length).map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})[\\s\\p{Script=Hiragana}]{0,4}(?:is|es|est|ist|é|è|:|:|=|は|是|为|為|은|는)?\\s*[\"'「『“]?([A-Za-z0-9][A-Za-z0-9-]{2,23})(?![A-Za-z0-9-])`, 'iu');
254
+ const NOT_A_CODE = /^(to|and|the|for|that|then|with|para|pour|und|der|que)$/i;
255
+
256
+ /** A short test code from a brief in any language, or null. */
257
+ export function codeFrom(brief) {
258
+ const m = CODE_RE.exec(norm(brief));
259
+ return m && !NOT_A_CODE.test(m[1]) ? m[1] : null;
260
+ }
261
+
262
+ /** Whether a label the playtester says it read is in a page's own text (null when the page gave none to check against). */
263
+ export function onScreen(label, texts) {
264
+ const want = fold(label).replace(/\s+/g, '');
265
+ const hay = (Array.isArray(texts) ? texts : [texts]).map(fold).join('\n').replace(/[ \t]+/g, '');
266
+ if (!want) return null;
267
+ if (!hay.trim()) return null;
268
+ return hay.includes(want);
269
+ }
270
+
271
+ /** Whether words the playtester quotes from the brief are in the brief. */
272
+ export function inBrief(words, brief) {
273
+ const want = fold(words).replace(/\s+/g, ' ').trim();
274
+ return Boolean(want) && fold(brief).replace(/\s+/g, ' ').includes(want);
275
+ }
276
+
277
+ /**
278
+ * The prompt lines about language: what the brief and the game are written
279
+ * in, how to act on a brief in one language over a game in another, and the
280
+ * language of the playtester's own prose. `game` is null until the screen
281
+ * has shown enough text to tell.
282
+ */
283
+ export function languageLines({ brief = null, game = null, report }) {
284
+ const lines = [];
285
+ const foreign = (game && game.code !== 'en') || (brief && brief.code !== 'en');
286
+ const differ = game && brief && game.code !== brief.code;
287
+ if (game && game.code !== 'en') lines.push(`The game's text is in ${game.name}. Read it as written and act on what it says; copy "reads" in ${game.name}, untranslated.`);
288
+ if (differ) lines.push(`The brief is in ${brief.name} and the game is in ${game.name}: when the brief names something (a faction, a character, a level, a mode, a button), find the option on screen that means the same in ${game.name}.`);
289
+ if (foreign) lines.push('When you pick something the brief names, add "chose":{"brief":"<the brief\'s words>","screen":"<the label on screen, as written>"} to that plan, so the choice can be checked against the screen.');
290
+ if (report && report.code !== 'en') lines.push(`Write "thought", "expect", every "notice" and anything else you write for the studio in ${report.name}, because ${report.why}. Keep the JSON keys and the action names in English.`);
291
+ return lines;
292
+ }
293
+
294
+ /** The one line a reflection or a report call is given about its language. */
295
+ export function reportLanguageLine(report) {
296
+ if (!report || report.code === 'en') return '';
297
+ return `Write every sentence of your answer in ${report.name}, because ${report.why}. Keep the JSON keys as they are.`;
298
+ }
299
+
300
+ // The other word lists the runner guards with, in the languages above. Each
301
+ // widens an English pattern that stays where it is used (lib/observe.mjs,
302
+ // lib/edgepass.mjs, lib/coverage.mjs), so a game in another language keeps
303
+ // the same guard.
304
+ const WORD_LISTS = {
305
+ // A level or the game cleared. A sign of progress, never the end of play.
306
+ win: ['ステージクリア', 'ゲームクリア', 'レベルクリア', 'クリア!', 'クリア!', '勝利', 'あなたの勝ち', '通关', '通關', '过关', '過關', '胜利', '你赢了', '你贏了', '승리', '클리어', '이겼습니다',
307
+ 'has ganado', 'ganaste', 'victoria', 'nivel completado', 'nivel superado', 'vous avez gagné', 'victoire', 'niveau terminé', 'niveau réussi', 'gewonnen', 'sieg', 'level geschafft', 'level abgeschlossen',
308
+ 'você venceu', 'vitória', 'nível concluído', 'fase concluída', 'hai vinto', 'vittoria', 'livello completato', 'победа', 'вы победили', 'уровень пройден', 'wygrałeś', 'zwycięstwo', 'poziom ukończony', 'kazandın', 'bölüm tamamlandı'],
309
+ // A control that deletes, spends or leaves: never pressed by the runner on its own.
310
+ risky: ['削除', '消去', 'リセット', '初期化', '終了', 'やめる', '購入', '買う', '支払', 'ログアウト', 'サインアウト', '删除', '刪除', '重置', '清除', '退出', '购买', '購買', '支付', '付款', '登出', '注销', '註銷',
311
+ '삭제', '초기화', '종료', '나가기', '구매', '결제', '로그아웃', 'eliminar', 'borrar', 'reiniciar', 'restablecer', 'salir', 'comprar', 'pagar', 'cerrar sesión', 'supprimer', 'effacer', 'réinitialiser', 'quitter', 'acheter', 'payer', 'déconnexion',
312
+ 'löschen', 'zurücksetzen', 'beenden', 'verlassen', 'kaufen', 'bezahlen', 'abmelden', 'excluir', 'apagar', 'redefinir', 'sair', 'elimina', 'cancella', 'reimposta', 'esci', 'compra', 'paga',
313
+ 'удалить', 'стереть', 'сбросить', 'выйти', 'выход', 'купить', 'оплатить', 'usuń', 'zresetuj', 'wyjdź', 'kup', 'zapłać', 'sıfırla', 'çıkış', 'satın al'],
314
+ // A control whose effect is only heard.
315
+ audio: ['音', 'サウンド', 'ミュート', 'ボイス', 'bgm', '静音', '靜音', '语音', '語音', '소리', '사운드', '음악', '음량', '음소거', '효과음', '음성', 'sonido', 'música', 'volumen', 'silenciar', 'musique', 'muet', 'voix',
316
+ 'musik', 'lautstärke', 'stumm', 'mudo', 'suono', 'musica', 'muto', 'voce', 'звук', 'музыка', 'громкость', 'dźwięk', 'muzyka', 'głośność', 'müzik']
317
+ };
318
+
319
+ /**
320
+ * An English pattern widened with the same words in other languages. The
321
+ * result is a RegExp (it works with both `test` and `exec`), case blind.
322
+ * Words in the Latin, Cyrillic and Greek alphabets must stand as words; the
323
+ * others match wherever they are written.
324
+ */
325
+ export function withLanguages(base, list) {
326
+ const words = WORD_LISTS[list];
327
+ if (!words) throw new Error(`unknown word list ${list}`);
328
+ const esc = w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
329
+ const spaced = w => /^[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Greek}\s]+$/u.test(w);
330
+ const more = words.map(w => (spaced(w) ? `(?<![\\p{L}])${esc(w)}(?![\\p{L}])` : esc(w))).join('|');
331
+ // The English pattern's \b is ASCII, which is what its words need; the rest carry their own bounds.
332
+ return new RegExp(`${base.source}|${more}`, 'iu');
333
+ }
334
+
335
+ /** The "moves the player on" check as a pattern-shaped object, for code that calls `.test(name)`. */
336
+ export const GOING_ON_ANY = Object.freeze({ test: goingOn });