ravensight-playtest 0.10.3 → 0.11.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.
@@ -0,0 +1,246 @@
1
+ // The local CLI carries this file unchanged from the hosted runner (the platform repo, lib/eventclaims.mjs).
2
+ // What the game's own events say about one of the playtester's claims.
3
+ //
4
+ // lib/events.mjs keeps a run's events (`run.gameEvents`), each placed at the
5
+ // step it happened. lib/claims.mjs gateClaim asks here, for every claim:
6
+ //
7
+ // contradicted the claim says something did not happen or did not change
8
+ // ("HP did not drop", "my attacks never land", "I never died",
9
+ // "the score stays at 0"), about the game itself rather than
10
+ // the screen, and the game's own events in the steps the claim
11
+ // is about show it did. The claim is turned away, like one the
12
+ // run's own record contradicts.
13
+ // confirmed the events show the fact the claim states: an error the game
14
+ // itself reported, a count with a value no game should have
15
+ // (below zero, NaN), or a count back to zero. It counts as
16
+ // verified in place of the frame showing it. Whether the game
17
+ // is at FAULT for it is a separate question (lib/claims.mjs),
18
+ // and only a fact that is a fault in itself (an error, an
19
+ // impossible value) answers that one too.
20
+ //
21
+ // Narrow on purpose. A wrong contradiction would hide a real defect, so the
22
+ // rules say nothing unless the claim's subject, whose it is and which way it
23
+ // moved all plainly match an event; anything else (a claim about how the
24
+ // screen shows something, a subject no event names, a sentence whose subject
25
+ // is something the events do not name) is left to the frame, exactly as for a
26
+ // game without the SDK.
27
+ const noDashes = s => String(s ?? '').replace(/[\u2013\u2014]/g, ',');
28
+
29
+ // What a claim may be about that a game's events measure: the words a claim uses, and the words an event's name or keys use.
30
+ const TOPICS = [
31
+ { id: 'hp', words: /\b(hp|health|hit ?points?|hearts?|vitality)\b/i, tokens: ['hp', 'health', 'heart', 'hitpoint', 'hitpoints', 'vitality'] },
32
+ { id: 'damage', words: /\b(damage\w*|dmg|hurt|harm\w*|wound\w*)\b/i, tokens: ['damage', 'damaged', 'dmg', 'hurt', 'harm', 'wound', 'wounded'] },
33
+ { id: 'hit', words: /\b(hits?|attacks?|strikes?|shots?|swings?|punch(?:es)?|kicks?|bullets?)\b/i, tokens: ['hit', 'attack', 'strike', 'shot', 'damage', 'dmg', 'damaged'] },
34
+ { id: 'death', words: /\b(die|dies|died|dying|death|dead|killed|game ?over)\b/i, tokens: ['die', 'died', 'death', 'dead', 'killed', 'kill', 'gameover', 'defeat', 'defeated'] },
35
+ { id: 'score', words: /\b(scores?|points?|pts)\b/i, tokens: ['score', 'point', 'points', 'pts'] },
36
+ { id: 'lives', words: /\blives\b/i, tokens: ['lives', 'life'] },
37
+ { id: 'coins', words: /\b(coins?|gold|money|gems?|cash)\b/i, tokens: ['coin', 'coins', 'gold', 'money', 'gem', 'gems', 'cash'] }
38
+ ];
39
+ const TOPIC = Object.fromEntries(TOPICS.map(t => [t.id, t]));
40
+ // Losing health is taking damage: a claim about one is answered by events about the other.
41
+ const RELATED = { hp: ['hp', 'damage'], damage: ['damage', 'hp'], hit: ['hit'], death: ['death'], score: ['score'], lives: ['lives', 'death'], coins: ['coins'] };
42
+ // Topics whose events carry a value (hp=3, score=40), and those whose event is the thing itself (damage_taken, player_died).
43
+ const VALUED = new Set(['hp', 'score', 'lives', 'coins']);
44
+ // Counts that can never go below zero in a game.
45
+ const NEVER_NEGATIVE = new Set(['score', 'coins', 'lives']);
46
+
47
+ // A claim that something did NOT happen or did not change, and which way it says it did not move.
48
+ const NEG = String.raw`(?:did ?n[o']?t|does ?n[o']?t|do ?n[o']?t|never|won'?t|will not|is ?n[o']?t|was ?n[o']?t|are ?n[o']?t|not|no longer|fails? to|failed to|cannot|can'?t|could ?n[o']?t)`;
49
+ const ANY = String.raw`(?:chang\w*|updat\w*|mov(?:e|es|ed|ing)|land\w*|connect\w*|register\w*|hit|hits|happen\w*|trigger\w*|work\w*|apply|appl(?:ies|ied)|deal\w*|dealt|do(?:es)? (?:any )?damage|die|dies|died|kill\w*|react\w*|respond\w*)`;
50
+ const DOWN = String.raw`(?:drop\w*|decreas\w*|go(?:es)? down|went down|gone down|fall\w*|fell|reduc\w*|lower\w*|deplet\w*|lose|loses|losing|lost|take|takes|taking|took|taken)`;
51
+ const UP = String.raw`(?:increas\w*|go(?:es)? up|went up|gone up|ris(?:e|es|ing)|rose|gain\w*|award\w*|add\w*|count\w*|grow\w*)`;
52
+ const negThen = verbs => new RegExp(String.raw`\b${NEG}\b(?:\s+[\w']+){0,3}?\s+${verbs}\b`, 'i');
53
+ const NEG_ANY = negThen(ANY), NEG_DOWN = negThen(DOWN), NEG_UP = negThen(UP);
54
+ const NEG_AT = new RegExp(String.raw`\b${NEG}\b`, 'i');
55
+ const STAYS = /\b(stays?|stayed|remains?|remained|unchanged|constant|stuck at|frozen at|the same)\b/i;
56
+ const NONE = /\b(?:no|zero|without)\s+(?:\w+\s+)?(?:damage|points?|score|hits?|death|coins?)\b|\b(?:immune|invincible|invulnerable|unkillable)\b|\b(?:can'?t|cannot|could ?n[o']?t|never) (?:be )?(?:die|died|killed|hurt|damaged)\b/i;
57
+ // Words about how the screen shows a thing, or about what the playtester could tell: the events say what the game did, not what
58
+ // the screen showed, so such a claim is left to the frame (an HP bar that does not move while the game's hp does is the screen's
59
+ // fault, and not for events to dismiss), and "I could not tell whether it hit" is a claim about clarity.
60
+ const NOT_STATE = /\b(show\w*|display\w*|visible|invisible|appear\w*|feedback|indicat\w*|animation\w*|animat\w*|flash\w*|sound\w*|effects?|pop ?ups?|text|bar|hud|icons?|ui|labels?|counter|readout|meter|marker|highlight\w*|numbers?|screen|drawn|render\w*|shake|particle\w*|tell\w*|clear\w*|unclear|obvious\w*|cue\w*|see|seen|saw|know\w*|sure|whether|understand\w*|seems?|seemed|feels?|felt|looks?|looked)\b/i;
61
+ // Who a thing belongs to: words for something other than the player.
62
+ const OTHER_ACTOR = /\b(enem(?:y|ies)|boss\w*|monsters?|foes?|opponents?|targets?|mobs?|creatures?|npcs?|rivals?|attackers?)\b/i;
63
+ const OTHER_TOKENS = new Set(['enemy', 'enemies', 'boss', 'monster', 'foe', 'opponent', 'target', 'mob', 'creature', 'npc', 'rival', 'attacker']);
64
+ // Words that leave a sentence's subject the player's own: articles, the player, and verbs and fillers that name no one.
65
+ const NO_ONE = new Set(['the', 'a', 'an', 'my', 'your', 'our', 'own', 'its', 'his', 'her', 'their', 'player', 'players', "player's", 'hero', "hero's", 'character', "character's", 'i', 'me', 'total', 'current', 'any', 'and', 'or', 'of', 'even', 'still', 'also', 'just', 'really', 'then', 'after', 'when', 'while', 'every', 'each', 'all', 'some', 'that', 'this', 'there', 'it', 'is', 'was', 'are', 'were', 'be', 'been', 'take', 'takes', 'taking', 'took', 'deal', 'deals', 'dealing', 'get', 'gets', 'getting', 'got', 'press', 'pressing', 'pressed', 'click', 'clicking', 'clicked', 'my', 'from', 'on', 'in', 'at', 'to', 'with', 'by', 'for', 'again', 'once', 'twice']);
66
+ // Damage one way or the other: dealt by the player, or taken by it.
67
+ const OUT_TOKENS = new Set(['dealt', 'deal', 'inflicted', 'inflict', 'outgoing']);
68
+ const IN_TOKENS = new Set(['taken', 'take', 'received', 'receive', 'incoming', 'suffered', 'hurt']);
69
+ const OUTGOING_CLAIM = /\b(deal\w*|dealt|inflict\w*|attacks?|shots?|strikes?|swings?|punch(?:es)?|kicks?|bullets?)\b/i;
70
+ const INCOMING_CLAIM = /\b(take\w*|took|taken|receiv\w*|hurt me|hit me|i was hit|get hit|got hit|i get|i got)\b/i;
71
+ // An event that says something was gained.
72
+ const GAINED = new Set(['collect', 'collected', 'pickup', 'picked', 'gain', 'gained', 'earn', 'earned', 'add', 'added', 'award', 'awarded', 'get', 'got']);
73
+
74
+ const tokensOf = s => String(s || '').replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
75
+ const withSingulars = t => { for (const w of [...t]) if (w.length > 3 && w.endsWith('s')) t.add(w.slice(0, -1)); return t; };
76
+ /** An event's name and keys as words ("playerHealth" is "player", "health"), and the name run together ("gameover"). */
77
+ const ownTokens = e => withSingulars(new Set([...tokensOf(e.name), tokensOf(e.name).join(''), ...Object.keys(e.props).flatMap(tokensOf)]));
78
+ const nameTokens = e => withSingulars(new Set([...tokensOf(e.name), tokensOf(e.name).join('')]));
79
+ /** Every word an event carries, its string values too ("source": "slime"). */
80
+ const allTokens = e => withSingulars(new Set([...ownTokens(e), ...Object.values(e.props).filter(v => typeof v === 'string').flatMap(tokensOf)]));
81
+ const isTopicWord = w => TOPICS.some(tp => tp.words.test(w));
82
+ const firstIndex = (t, res) => res.map(re => { const m = re.exec(t); return m ? m.index : -1; }).filter(i => i >= 0).reduce((a, b) => Math.min(a, b), Infinity);
83
+
84
+ /**
85
+ * What a claim is about, as far as events can answer it: `{ topic, actor, outgoing, way, state }`, or null when it names no
86
+ * subject an event measures. `actor.other` is true when the sentence's subject is something other than the player ("the
87
+ * slime", "enemy health"), with the words that name it. `way` is how it says the thing did not move: 'down', 'up', 'any' or
88
+ * null (it does not say that). `state` is false for a claim about the screen or about what the playtester could tell.
89
+ */
90
+ export function claimAboutEvents(title) {
91
+ const t = noDashes(String(title || '')).replace(/\s+/g, ' ').trim();
92
+ if (!t) return null;
93
+ let topic = null, index = Infinity;
94
+ for (const tp of TOPICS) {
95
+ const m = tp.words.exec(t);
96
+ if (m && m.index < index) { topic = tp; index = m.index; }
97
+ }
98
+ if (!topic) return null;
99
+ // The subject: the words before the claim says "not" (or "stays", "no"), else before the topic word. Whatever is left there
100
+ // once articles, the player, verbs and the topic words are taken out names someone other than the player.
101
+ const cut = Math.min(firstIndex(t, [NEG_AT, STAYS, NONE]), index);
102
+ const subject = t.slice(0, Number.isFinite(cut) ? cut : 0).toLowerCase().split(/[^a-z']+/).filter(Boolean);
103
+ const named = subject.map(w => w.replace(/'s$/, '')).filter(w => w.length >= 3 && !NO_ONE.has(w) && !isTopicWord(w) && !/^(?:attack\w*|hit\w*|shoot\w*|jump\w*|mov\w*|walk\w*|run\w*)$/.test(w));
104
+ const actor = { other: named.length > 0 || OTHER_ACTOR.test(subject.join(' ')), words: named };
105
+ const outgoing = topic.id === 'hit' || (topic.id === 'damage' && OUTGOING_CLAIM.test(t) && !INCOMING_CLAIM.test(t));
106
+ const way = NEG_ANY.test(t) ? 'any' : NEG_DOWN.test(t) ? 'down' : NEG_UP.test(t) ? 'up' : NONE.test(t) || STAYS.test(t) ? 'any' : null;
107
+ return { topic: topic.id, actor, outgoing, way, state: !NOT_STATE.test(t), text: t };
108
+ }
109
+
110
+ /** Whether an event is about the claim's subject, for the same one (the player, or what the claim names) and the same way. */
111
+ export function eventMatches(e, about, { byName = false } = {}) {
112
+ const words = byName ? nameTokens(e) : ownTokens(e);
113
+ const topics = RELATED[about.topic] || [about.topic];
114
+ if (!topics.some(id => TOPIC[id].tokens.some(w => words.has(w)))) return false;
115
+ const own = ownTokens(e), all = allTokens(e);
116
+ const otherInEvent = [...own].some(w => OTHER_TOKENS.has(w));
117
+ if (about.outgoing) {
118
+ // Damage the player deals: never an event of damage taken, and only one that says it went to someone else.
119
+ if ([...own].some(w => IN_TOKENS.has(w))) return false;
120
+ if (about.actor.other && about.actor.words.length) return about.actor.words.some(w => all.has(w));
121
+ return otherInEvent || [...own].some(w => OUT_TOKENS.has(w));
122
+ }
123
+ if (about.actor.other) return about.actor.words.length ? about.actor.words.some(w => all.has(w)) : otherInEvent;
124
+ // The player's own: never an event about an enemy, or about damage the player dealt.
125
+ return !otherInEvent && ![...own].some(w => OUT_TOKENS.has(w));
126
+ }
127
+
128
+ /** The numeric property of an event that holds the topic's value ("hp", "score", "playerHealth"), or null. */
129
+ function valueKey(e, about) {
130
+ const tokens = (RELATED[about.topic] || [about.topic]).filter(id => VALUED.has(id)).flatMap(id => TOPIC[id].tokens);
131
+ return Object.keys(e.props).find(k => typeof e.props[k] === 'number' && tokensOf(k).some(w => tokens.includes(w) || tokens.includes(w.replace(/s$/, '')))) || null;
132
+ }
133
+
134
+ const propsText = props => Object.entries(props).map(([k, v]) => `${k}=${v}`).join(' ');
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}` : '');
137
+
138
+ /** 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
+ function windowOf(claim) {
140
+ if (claim.inputs && Number.isSafeInteger(claim.inputs.from) && Number.isSafeInteger(claim.inputs.to)) return { from: claim.inputs.from, to: Math.max(claim.inputs.from, claim.inputs.to) };
141
+ if (!Number.isSafeInteger(claim.step)) return null;
142
+ return { from: Math.max(0, claim.step - 4), to: claim.step };
143
+ }
144
+
145
+ const ERROR_CLAIM = /\b(errors?|exceptions?|crash\w*)\b/i;
146
+ const IMPOSSIBLE = /\b(nan|undefined|null|negative|below zero|less than zero|minus)\b|(?:^|\s)-\d/i;
147
+ const RESET = /\b(?:reset\w*(?: back)?(?: to)?|went back to|goes back to|back to|dropp?(?:ed|s)? to|fell to|falls to|went to|goes to) (?:0|zero)\b/i;
148
+ const ODD_VALUE = /^(?:nan|undefined|null|infinity|-infinity)$/i;
149
+
150
+ const memo = new WeakMap();
151
+ /** The verdicts the gate reached on this run, by claim title: for the report (lib/events.mjs). */
152
+ export const eventsDecided = run => (run && memo.get(run)) || new Map();
153
+
154
+ /**
155
+ * What the game's own events say about a claim (`{ title, step, inputs }`): `{ verdict: 'contradicted' | 'confirmed', why,
156
+ * events, fault? }`, or null when they cannot speak to it. Null for every run without the SDK (`run.gameEvents` null or
157
+ * empty), so such a run's gate is exactly what it was. See the top of this file for the rules.
158
+ */
159
+ export function eventsVerdict(run, claim) {
160
+ const evs = run?.gameEvents?.events;
161
+ if (!Array.isArray(evs) || !evs.length || !claim) return null;
162
+ const win = windowOf(claim);
163
+ if (!win) return null;
164
+ 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);
166
+ const done = (verdict, why, list, extra = {}) => {
167
+ const v = { verdict, why: noDashes(why), events: list.slice(0, 4).map(e => ({ step: e.step, name: e.name, props: e.props })), ...extra };
168
+ if (!memo.has(run)) memo.set(run, new Map());
169
+ memo.get(run).set(title, v);
170
+ return v;
171
+ };
172
+
173
+ // An error the game itself reported, in the steps the claim is about: a fault in itself.
174
+ if (ERROR_CLAIM.test(title) && !NEG_AT.test(title) && !/\bno\b/i.test(title)) {
175
+ const errs = inWin.filter(e => e.name === 'error' || e.props.rs_kind === 'error');
176
+ if (errs.length) return done('confirmed', `the game itself reported an error${atStep(errs[0])}: ${show(errs[0])}`, errs, { fault: true });
177
+ }
178
+ const about = claimAboutEvents(title);
179
+ if (!about) return null;
180
+ const matching = inWin.filter(e => eventMatches(e, about));
181
+ if (!matching.length) return null;
182
+
183
+ // Confirmations: a value no game should have, or a count back to zero.
184
+ if (IMPOSSIBLE.test(title) || RESET.test(title)) {
185
+ if (IMPOSSIBLE.test(title)) {
186
+ for (const e of matching) {
187
+ const odd = Object.entries(e.props).find(([k, v]) => tokensOf(k).some(w => TOPIC[about.topic].tokens.includes(w)) && (v === null || ODD_VALUE.test(String(v))));
188
+ if (odd) return done('confirmed', `the game's own event${atStep(e)} carried ${odd[0]}=${odd[1]}: ${show(e)}`, [e], { fault: true });
189
+ const k = valueKey(e, about);
190
+ if (k && e.props[k] < 0) return done('confirmed', `the game's own event${atStep(e)} carried ${k}=${e.props[k]}, below zero: ${show(e)}`, [e], { fault: NEVER_NEGATIVE.has(about.topic) });
191
+ }
192
+ }
193
+ if (RESET.test(title)) {
194
+ // A value of zero after the same count stood above zero earlier in the steps the claim is about.
195
+ const series = matching.map(e => ({ e, k: valueKey(e, about) })).filter(x => x.k);
196
+ const high = new Map();
197
+ for (const { e, k } of series) {
198
+ const v = e.props[k];
199
+ if (v === 0 && high.has(k)) { const a = high.get(k); return done('confirmed', `the game's own events show ${k} go from ${a.props[k]}${atStep(a)} to 0${atStep(e)}`, [a, e], { fault: false }); }
200
+ if (v > 0) high.set(k, e);
201
+ }
202
+ }
203
+ return null;
204
+ }
205
+
206
+ // Contradictions: only a claim that something did not happen or did not change, about the game rather than the screen.
207
+ if (!about.way || !about.state) return null;
208
+ // A value that moved the way the claim says it did not, compared with the last value before the window too.
209
+ 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
+ for (let i = 1; i < keyed.length; i++) {
211
+ const a = keyed[i - 1], b = keyed[i];
212
+ if (b.e.step < win.from || a.k !== b.k) continue;
213
+ const from = a.e.props[a.k], to = b.e.props[b.k];
214
+ if (from === to) continue;
215
+ 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]);
216
+ }
217
+ // An event whose own name is the thing the claim says did not happen ("damage_taken", "player_died", "enemy_hit", "coin_collected").
218
+ const named = matching.filter(e => {
219
+ if (!eventMatches(e, about, { byName: true })) return false;
220
+ const words = nameTokens(e);
221
+ // Damage, a hit or a death named by the event happened: it answers a claim that it did not, or that health did not go down.
222
+ if (['damage', 'hit', 'death'].some(id => (RELATED[about.topic] || []).includes(id) && TOPIC[id].tokens.some(w => words.has(w)))) return about.way !== 'up';
223
+ // A count the event names: its value decides above; with no value, only a gain ("coin_collected") answers "did not go up".
224
+ if (VALUED.has(about.topic) && !valueKey(e, about)) return about.way === 'any' || (about.way === 'up' && [...words].some(w => GAINED.has(w)));
225
+ return false;
226
+ });
227
+ if (named.length) {
228
+ const first = named[0];
229
+ return done('contradicted', `the game itself sent ${show(first)}${atStep(first)}${named.length > 1 ? `, and ${named.length - 1} more like it by step ${named.at(-1).step}` : ''}`, named);
230
+ }
231
+ return null;
232
+ }
233
+
234
+ /**
235
+ * The gate's use of a confirmation (lib/claims.mjs gateClaim, for a claim of fact): the fields to add to its pass, or
236
+ * null. When the check asked whether the game is at fault, only a fact that is a fault in itself (`fault: true`) stands in
237
+ * for the frame's "game at fault".
238
+ */
239
+ export function eventsConfirmed(ev, question = null) {
240
+ if (!ev || ev.verdict !== 'confirmed') return null;
241
+ if (question === 'fault' && !ev.fault) return null;
242
+ return { evidence: 'events', events: ev.events };
243
+ }
244
+
245
+ /** The reason the gate gives for a claim the events contradict. */
246
+ export const contradictedReason = ev => `the game's own events contradict it: ${ev.why}`;
@@ -0,0 +1,354 @@
1
+ // The local CLI carries this file unchanged from the hosted runner (the platform repo, lib/events.mjs).
2
+ // In the local CLI the play loop hands it the events a local game sends: the Godot driver's mirror, or the web SDK's calls.
3
+ // The game's own analytics events as the playtester's ground truth.
4
+ //
5
+ // A game that ships the Ravensight SDK already reports what happened in it:
6
+ // damage taken, the score, a death, an error. The playtester otherwise sees
7
+ // only pixels, and its claims are judged from frames. Here the runner reads
8
+ // those events where it already holds them: the SDK's ingest calls pass
9
+ // through the runner's ingest proxy (lib/network.mjs), so `tap` sees each
10
+ // track body in the runner process as the game sent it. Nothing new leaves
11
+ // the sandbox, the page holds nothing new, and forwarding is unchanged: the
12
+ // proxy still forwards the same calls, tagged as this run's synthetic
13
+ // playtest data. See docs/superpowers/specs/2026-11-14-playtest-events-ground-truth.md.
14
+ //
15
+ // Three uses, each kept small and bounded:
16
+ // play the planner is told, in its next plan request, the events since
17
+ // its last one (`pendingForPlan`, lib/combined.mjs);
18
+ // gate a claim the events contradict is turned away, and a claim of
19
+ // fact the events confirm counts as verified (lib/eventclaims.mjs,
20
+ // asked by lib/claims.mjs gateClaim);
21
+ // report a section and a usage record of what was measured from the
22
+ // game's own events (`eventsReportLines`, `eventsUsage`).
23
+ //
24
+ // Each event is placed at the step its own timestamp falls in: the runner
25
+ // reads the page's clock (game time, under the time gate) just before each
26
+ // input. An SDK sends in batches, seconds of game time after an event
27
+ // happened, so arrival order says little; the timestamp says when.
28
+ //
29
+ // Event names, keys and values are the build's own strings: untrusted. They
30
+ // are cut short and stripped of anything but plain characters before they
31
+ // reach a prompt or a report, and the prompt carries them after its
32
+ // untrusted-data line.
33
+ import zlib from 'node:zlib';
34
+ const noDashes = s => String(s ?? '').replace(/[\u2013\u2014]/g, ',');
35
+ import { eventsDecided } from './eventclaims.js';
36
+
37
+ export const EVENT_LIMITS = Object.freeze({
38
+ // What one run keeps. A run is a few hundred inputs; a game that sends more than this is counted, not kept.
39
+ events: 2000,
40
+ // One request body, inflated. The proxy already refuses a body over the server's own 512 KB.
41
+ inflatedBytes: 1024 * 1024,
42
+ perBody: 200,
43
+ nameChars: 48,
44
+ props: 10,
45
+ keyChars: 32,
46
+ valueChars: 48,
47
+ // The planner's share of a plan request: lines, and characters over all of them.
48
+ planLines: 8,
49
+ planChars: 900,
50
+ // The report and usage.json.
51
+ reportLines: 12,
52
+ usageEvents: 300,
53
+ // How long the runner waits for one page clock reading.
54
+ markMs: 1500,
55
+ // The final flush: quiet for this long ends it, and it never takes longer than the cap.
56
+ flushQuietMs: 400,
57
+ flushMaxMs: 2500
58
+ });
59
+
60
+ // What the SDKs send about themselves rather than about play: counted, never shown to the planner.
61
+ const SYSTEM_EVENTS = new Set(['game_started', 'game_exited', 'session_start', 'session_end', 'health', 'rs_exposure', 'heartbeat', 'app_start', 'app_exit']);
62
+ export const systemEvent = name => SYSTEM_EVENTS.has(name) || /^(?:rs_|\$)/.test(name);
63
+
64
+ /** The build's text, made safe for a prompt and a report: plain characters only, cut short. */
65
+ export function cleanText(value, max) {
66
+ return noDashes(String(value ?? '')).normalize('NFKC').replace(/[^\p{L}\p{N} _.:/#%+(),-]+/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
67
+ }
68
+ const cleanKey = k => String(k ?? '').replace(/[^A-Za-z0-9_.-]+/g, '').slice(0, EVENT_LIMITS.keyChars);
69
+
70
+ /** One property value as kept: a finite number, a boolean, a short clean string, or null. Objects are left out. */
71
+ function cleanValue(v) {
72
+ if (typeof v === 'number') return Number.isFinite(v) ? v : String(v);
73
+ if (typeof v === 'boolean' || v === null) return v;
74
+ if (typeof v === 'string') {
75
+ // A number sent as text ("3") is still a number to compare.
76
+ const t = v.trim();
77
+ if (/^-?\d+(?:\.\d+)?$/.test(t) && t.length <= 15) return Number(t);
78
+ return cleanText(t, EVENT_LIMITS.valueChars);
79
+ }
80
+ return undefined;
81
+ }
82
+
83
+ /** An event's top-level properties, bounded. The SDKs' own tags (rs_*, pt_*) are left out except the error kind. */
84
+ export function cleanProps(data) {
85
+ const out = {};
86
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return out;
87
+ let n = 0;
88
+ for (const [k0, v0] of Object.entries(data)) {
89
+ if (n >= EVENT_LIMITS.props) break;
90
+ if (/^(?:rs|pt)_/i.test(k0) && k0 !== 'rs_kind') continue;
91
+ const k = cleanKey(k0), v = cleanValue(v0);
92
+ if (!k || v === undefined) continue;
93
+ out[k] = v;
94
+ n++;
95
+ }
96
+ return out;
97
+ }
98
+
99
+ /** Unix milliseconds from an SDK timestamp (milliseconds, or seconds from an older SDK), or null. */
100
+ function timestampOf(raw) {
101
+ let t = Number(raw);
102
+ if (!Number.isFinite(t) || t <= 0) return null;
103
+ if (t < 1e11) t *= 1000;
104
+ return Math.floor(t);
105
+ }
106
+
107
+ /**
108
+ * The events in one track request body, as the SDKs send them: `{ events: [...] }`
109
+ * (a batch), `{ event, data, timestamp }` (one), either gzip compressed, or a
110
+ * signed body that carries the text inside. Answers `[{ name, props, ts }]`,
111
+ * empty for anything else. Never throws.
112
+ */
113
+ export function parseTrackBody(body, headers = {}) {
114
+ try {
115
+ let buf = Buffer.isBuffer(body) ? body : Buffer.from(body == null ? '' : String(body));
116
+ if (!buf.length) return [];
117
+ const encoding = String(headers['content-encoding'] || '').toLowerCase();
118
+ if (encoding === 'gzip' || (buf[0] === 0x1f && buf[1] === 0x8b)) buf = zlib.gunzipSync(buf, { maxOutputLength: EVENT_LIMITS.inflatedBytes });
119
+ if (buf.length > EVENT_LIMITS.inflatedBytes) return [];
120
+ let json = JSON.parse(buf.toString('utf8'));
121
+ if (json && typeof json.signed?.body === 'string') json = JSON.parse(json.signed.body);
122
+ const list = Array.isArray(json?.events) ? json.events : json && typeof json.event === 'string' ? [json] : [];
123
+ const out = [];
124
+ for (const e of list.slice(0, EVENT_LIMITS.perBody)) {
125
+ if (!e || typeof e.event !== 'string') continue;
126
+ const name = cleanText(e.event, EVENT_LIMITS.nameChars);
127
+ if (!name) continue;
128
+ // The SDK's own id for an event, when it sends one: a retry carries the same id.
129
+ 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 } : {}) });
131
+ }
132
+ return out;
133
+ } catch {
134
+ return [];
135
+ }
136
+ }
137
+
138
+ const propsText = props => Object.entries(props).map(([k, v]) => `${k}=${v}`).join(' ');
139
+ const stableKey = e => `${e.name}|${e.ts ?? ''}|${JSON.stringify(Object.entries(e.props).sort(([a], [b]) => (a < b ? -1 : 1)))}`;
140
+
141
+ /**
142
+ * One run's (one mode's) event log. `tap` is given to the ingest proxy;
143
+ * `markPage` is called by the play loop just before each input, and with
144
+ * 'end' when play ends; `flush` asks the SDK to send what it still holds
145
+ * before the page closes; `pendingForPlan` and `planned` feed the planner;
146
+ * `record` is what the run keeps (`run.gameEvents`).
147
+ */
148
+ export function createGameEvents({ now = Date.now, limits = EVENT_LIMITS } = {}) {
149
+ const events = [];
150
+ const keys = new Set();
151
+ const marks = [];
152
+ let total = 0, dropped = 0, duplicates = 0, bodies = 0, lastTapAt = 0, shownUpTo = 0, untimed = 0;
153
+
154
+ /** The proxy hands over each track call it passed: `{ body, headers }`. */
155
+ function tap({ body, headers = {} } = {}) {
156
+ bodies++;
157
+ lastTapAt = now();
158
+ // A body sent again (an SDK's retry) is the same events: an untimed event is known by its body and its place in it.
159
+ const bodyKey = Buffer.isBuffer(body) ? body.length + ':' + body.subarray(0, 64).toString('hex') : String(body).slice(0, 64);
160
+ parseTrackBody(body, headers).forEach((e, i) => {
161
+ const key = e.id ? `id|${e.id}` : e.ts === null ? `${stableKey(e)}|${bodyKey}|${i}` : stableKey(e);
162
+ if (keys.has(key)) { duplicates++; return; }
163
+ keys.add(key);
164
+ total++;
165
+ if (events.length >= limits.events) { dropped++; return; }
166
+ if (e.ts === null) untimed++;
167
+ const { id: _id, ...kept } = e;
168
+ events.push({ seq: events.length, ...kept, arrivedAt: lastTapAt });
169
+ });
170
+ }
171
+
172
+ /** The page's clock (game time under the time gate) at a step: `step` is the step number about to be played, or 'end'. */
173
+ function mark(step, pageMs) {
174
+ marks.push({ step, pageMs: Number.isFinite(pageMs) ? pageMs : null, realAt: now() });
175
+ }
176
+
177
+ async function markPage(page, step) {
178
+ let ms = null;
179
+ try {
180
+ ms = await Promise.race([Promise.resolve().then(() => page.evaluate(() => Date.now())).catch(() => null), new Promise(resolve => setTimeout(() => resolve(null), limits.markMs))]);
181
+ } catch { ms = null; }
182
+ mark(step, ms);
183
+ }
184
+
185
+ /**
186
+ * Where an event belongs: `{ phase: 'before' | 'play' | 'after', step, by }`.
187
+ * By its own timestamp against the page clock marks when it can be (`by:
188
+ * 'clock'`); by when it reached the runner otherwise (`by: 'arrival'`).
189
+ */
190
+ function place(e) {
191
+ const timed = marks.filter(m => m.pageMs !== null);
192
+ if (e.ts !== null && timed.length) {
193
+ const first = timed[0], last = timed.at(-1);
194
+ // A clock that is not the page's own (an engine that keeps its own) is read by arrival instead.
195
+ 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');
197
+ }
198
+ return at(marks, m => m.realAt <= e.arrivedAt, 'arrival');
199
+ }
200
+ const at = (list, before, by) => {
201
+ let found = null;
202
+ for (const m of list) if (before(m)) found = m;
203
+ if (!found) return { phase: 'before', step: null, by };
204
+ if (found.step === 'end') return { phase: 'after', step: null, by };
205
+ return { phase: 'play', step: found.step, by };
206
+ };
207
+
208
+ /** The events since the last plan, as lines for the planner, and the mark to give `planned` once the plan request was answered. */
209
+ function pendingForPlan() {
210
+ const fresh = events.slice(shownUpTo).filter(e => !systemEvent(e.name));
211
+ return { lines: planLines(fresh.map(e => ({ ...e, ...place(e) })), limits), upTo: events.length };
212
+ }
213
+ function planned(upTo) { if (Number.isSafeInteger(upTo) && upTo > shownUpTo) shownUpTo = Math.min(upTo, events.length); }
214
+
215
+ /**
216
+ * Ask the game's SDK to send what it still holds, as it does when a tab is
217
+ * hidden or a page is left: game time runs again, the page is shown as a
218
+ * background tab (visibility hidden, blur), and the runner waits until no
219
+ * track call has come for a moment. Only once play, the passes after it and
220
+ * every screenshot are done: it changes nothing anyone reads after it.
221
+ */
222
+ async function flush({ page, gate = null, sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) {
223
+ const started = now();
224
+ try {
225
+ if (gate) { await gate.resume().catch(() => {}); await gate.setHidden(true).catch(() => {}); }
226
+ else {
227
+ await page.evaluate(() => {
228
+ try { Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }); } catch { /* read only */ }
229
+ try { Object.defineProperty(document, 'hidden', { configurable: true, get: () => true }); } catch { /* read only */ }
230
+ document.dispatchEvent(new Event('visibilitychange'));
231
+ window.dispatchEvent(new Event('blur'));
232
+ window.dispatchEvent(new Event('pagehide'));
233
+ }).catch(() => {});
234
+ }
235
+ } catch { /* best effort */ }
236
+ const from = bodies;
237
+ while (now() - started < limits.flushMaxMs) {
238
+ await sleep(100);
239
+ if (now() - Math.max(lastTapAt, started) >= limits.flushQuietMs && (bodies > from || now() - started >= limits.flushQuietMs * 2)) break;
240
+ }
241
+ return { bodies: bodies - from, ms: now() - started };
242
+ }
243
+
244
+ /** What the run keeps: every event placed at its step, and the counts. */
245
+ function record() {
246
+ const placed = events.map(e => ({ seq: e.seq, name: e.name, props: e.props, ts: e.ts, ...place(e) }));
247
+ const by = placed.reduce((o, e) => { o[e.by] = (o[e.by] || 0) + 1; return o; }, {});
248
+ const names = {};
249
+ 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 };
251
+ }
252
+
253
+ return { tap, mark, markPage, flush, pendingForPlan, planned, record, get size() { return events.length; } };
254
+ }
255
+
256
+ const stepWords = e => (e.phase === 'before' ? 'before the first input' : e.phase === 'after' ? 'after play' : `step ${e.step}`);
257
+
258
+ /**
259
+ * Events as short lines for the planner: each kind of event on one line, in
260
+ * the order the kinds first came ("steps 4 to 7: score_changed 4 times, score 10, 20, 30, 40"),
261
+ * at most `planLines` lines and `planChars` characters.
262
+ */
263
+ export function planLines(placed, limits = EVENT_LIMITS) {
264
+ // One line per kind of event (and part of the run), in the order each kind first came: a fight's hits and the damage they
265
+ // brought interleave, and two lines say it more plainly than six.
266
+ const groups = [];
267
+ const byKey = new Map();
268
+ for (const e of placed) {
269
+ const key = `${e.phase}|${e.name}`;
270
+ if (!byKey.has(key)) { const g = { name: e.name, phase: e.phase, items: [] }; byKey.set(key, g); groups.push(g); }
271
+ byKey.get(key).items.push(e);
272
+ }
273
+ const lines = [];
274
+ let chars = 0, left = 0;
275
+ for (const g of groups) {
276
+ const first = g.items[0], last = g.items.at(-1);
277
+ let line;
278
+ if (g.items.length === 1) line = `${stepWords(first)}: ${g.name}${Object.keys(first.props).length ? ` ${propsText(first.props)}` : ''}`;
279
+ else {
280
+ const where = first.phase === 'play' && first.step !== last.step ? `steps ${first.step} to ${last.step}` : stepWords(first);
281
+ // A number that changed along the run is listed in order (the last few); anything else is said once, as the last event had it.
282
+ const numeric = Object.keys(last.props).filter(k => typeof last.props[k] === 'number');
283
+ const series = numeric.map(k => `${k} ${g.items.map(i => i.props[k]).filter(v => v !== undefined).slice(-6).join(', ')}`);
284
+ const rest = Object.entries(last.props).filter(([k]) => !numeric.includes(k)).map(([k, v]) => `${k}=${v}`);
285
+ line = `${where}: ${g.name} ${g.items.length} times${series.length || rest.length ? `, ${[...series, ...rest].join('; ')}` : ''}`;
286
+ }
287
+ line = line.slice(0, 200);
288
+ if (lines.length >= limits.planLines || chars + line.length > limits.planChars) { left += g.items.length; continue; }
289
+ lines.push(line);
290
+ chars += line.length;
291
+ }
292
+ if (left) lines.push(`and ${left} more event${left === 1 ? '' : 's'}`);
293
+ return lines;
294
+ }
295
+
296
+ /** The plan request's fixed line about the events (before its untrusted-data line), or ''. */
297
+ export const EVENTS_RULE = 'Below the line are events the game itself sent through its own Ravensight analytics since your last plan, each at the step it happened (they can arrive a few steps late). They are measured, not read off the picture: use them to tell whether an input landed, whether you took damage or died, and what the score is, and never report that something did not happen when an event shows it did.';
298
+ /** The events part of a plan request, after its untrusted-data line, or ''. */
299
+ export const eventsBlock = lines => (Array.isArray(lines) && lines.length ? `Game events since your last plan, by kind, in the order each first came:\n${lines.map(l => `- ${l}`).join('\n')}` : '');
300
+
301
+ // The gate's rules on what events say about a claim are in lib/eventclaims.mjs.
302
+
303
+ // ---- The report ------------------------------------------------------------------------------------------------------
304
+
305
+ /** The findings the game's own events confirmed, each with one more sentence saying so. Returns the same list. */
306
+ export function withEventEvidence(findings, run) {
307
+ const decided = eventsDecided(run);
308
+ for (const f of findings || []) {
309
+ const v = decided.get(f.title);
310
+ if (v?.verdict === 'confirmed' && typeof f.description === 'string' && !f.description.includes('Measured from the game\'s own events')) {
311
+ f.description = `${f.description} Measured from the game's own events: ${v.why}.`.slice(0, 2000);
312
+ }
313
+ }
314
+ return findings;
315
+ }
316
+
317
+ /** Whether a finding was confirmed by the game's own events (usage.json `finding_basis` says 'events'). */
318
+ export const eventBacked = (run, f) => eventsDecided(run).get(f?.title)?.verdict === 'confirmed';
319
+
320
+ /** The report's section, or nothing at all for a run where the game sent nothing through its SDK. */
321
+ export function eventsReportLines(run, { findings = [], turnedAway = [] } = {}) {
322
+ const g = run?.gameEvents;
323
+ if (!g || (!g.total && !(run.safety?.sdkTelemetry?.sessions > 0))) return [];
324
+ const md = ['## Measured from the game\'s own events', ''];
325
+ if (!g.total) {
326
+ md.push('The game opened a session through its own Ravensight SDK but sent no events during play, so nothing in this report was measured from them.', '');
327
+ return md;
328
+ }
329
+ 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.` : ''}`);
331
+ md.push('');
332
+ const decided = eventsDecided(run);
333
+ const confirmed = (findings || []).filter(f => decided.get(f.title)?.verdict === 'confirmed');
334
+ const contradicted = (turnedAway || []).filter(t => decided.get(t.title)?.verdict === 'contradicted');
335
+ for (const f of confirmed) md.push(`- Confirmed by the game's own events: "${cleanText(f.title, 120)}". ${decided.get(f.title).why}.`);
336
+ for (const t of contradicted) md.push(`- Contradicted by the game's own events, so not reported as a finding: "${cleanText(t.title, 120)}". ${decided.get(t.title).why}.`);
337
+ if (!confirmed.length && !contradicted.length) md.push('- No claim of the playtester\'s was about something these events measure, so they confirmed and contradicted nothing.');
338
+ md.push('');
339
+ const shown = g.events.filter(e => !systemEvent(e.name)).slice(0, EVENT_LIMITS.reportLines);
340
+ if (shown.length) {
341
+ md.push('The first events, in order:', '');
342
+ for (const e of shown) md.push(`- ${stepWords(e)}: ${e.name}${Object.keys(e.props).length ? `, ${propsText(e.props)}` : ''}`);
343
+ md.push('');
344
+ }
345
+ return md;
346
+ }
347
+
348
+ /** usage.json `gameEvents`: the counts, the verdicts and the first events, bounded. Null for a run with no event log. */
349
+ export function eventsUsage(run) {
350
+ const g = run?.gameEvents;
351
+ if (!g) return null;
352
+ 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 })) };
354
+ }